简体   繁体   English

将事件传递给骨干中的集合

[英]Passing an event to a collection in backbone

I am trying to trigger behaviour on a collection by triggering an event elsewhere in my app. 我试图通过触发应用程序中其他位置的事件来触发集合上的行为。 I am pretty new to backbone, so probably have all my syntax wrong, but this seems like it should work 我对骨干网还很陌生,所以可能我的语法都错了,但这似乎应该可行

fiddle 小提琴

var Test = Backbone.Model.extend({
});
var Tests = Backbone.Collection.extend({
        model: Test,
        events: {
            "testEvent":"testResponce"
        },
        testResponce: function(){
            alert('hello world');
        }
    });



var myTest = new Test();

myTest.trigger('testEvent');

Can this be done? 能做到吗? Where am I going wrong? 我要去哪里错了?

The event that you are triggering will have to be caught inside the model. 您触发的事件必须在模型中捕获。

If you want to catch an event inside collection you can use Backbone.on and Backbone.trigger OR collection.on and collection.trigger 如果要捕获集合中的事件,可以使用Backbone.onBackbone.triggercollection.oncollection.trigger

Please check the fiddle below for an example 请检查以下小提琴作为示例

fiddle 小提琴

var Test = Backbone.Model.extend({});
var Tests = Backbone.Collection.extend({
    model: Test,
    initialize: function () {
        Backbone.on('testEvent', function () {
            alert('event handled in collection');
        });
    }
});


var myCollection = new Tests();
var myTest = new Test();

Backbone.trigger('testEvent');

UPDATE UPDATE

Collection has an initialize method which you can use to register events on. 集合具有一个初始化方法 ,可用于注册事件。 Later you can trigger these events from their instances. 稍后,您可以从其实例触发这些事件。

Other way as NULL suggested is to do it like below. NULL建议的另一种方法是像下面这样。

var Test = Backbone.Model.extend({});
var Tests = Backbone.Collection.extend({
    model: Test,
    initialize: function () {
        this.on('testEvent', function () {
            alert('event handled in collection');
        });
    }
});


var myCollection = new Tests();
var myTest = new Test();

myCollection.trigger('testEvent');

If you want to call a particular method of your collection using testEvent event then you can take this path also. 如果要使用testEvent事件调用集合的特定方法,则也可以采用此路径。 Working Demo 工作演示

var Test = Backbone.Model.extend({
    initialize: function() {
        this.on('testEvent', function() {
            console.log(this.collection);
            this.collection.testResponce();
        });
    }
});
var Tests = Backbone.Collection.extend({
        model: Test,
        testResponce: function(){
            alert('hello world');
        }
    });

var myTest = new Test();
var testList = new Tests([myTest]);
myTest.trigger('testEvent');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM