Mild Fuzz
Mild Fuzz

Reputation: 30813

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?

Upvotes: 1

Views: 69

Answers (2)

Sachin Jain
Sachin Jain

Reputation: 21842

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

Upvotes: 1

Dhiraj
Dhiraj

Reputation: 33628

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

Upvotes: 1

Related Questions