简体   繁体   中英

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

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

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.

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. 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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