Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone pass object with event

Reading up on tutorials of Backbone, it seems that when the add event is fired from a collection, the item added is sent along with the event (same goes for remove). I can't find any documentation on this feature on the backbonejs.org site and was curious if there was a way I could send an object along with my custom events. Secondly, is something like this possible in Marionette?

like image 447
Tyler DeWitt Avatar asked Jan 23 '26 13:01

Tyler DeWitt


1 Answers

Each object defined by Backbone mixes in Backbone.Events which means you can trigger events with object.trigger. It is defined as

trigger object.trigger(event, [*args])
Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

You just have to pass additional arguments to get them in your callbacks.

For example,

var m = new Backbone.Model();
m.on('custom', function(more) {
     console.log(more);
});
m.trigger('custom', 'more info');

will log more info

See http://jsfiddle.net/nikoshr/HpwXe/ for a demo

You would trigger an event with a reference to the object to emulate the behavior of backbone :

var m = new Backbone.Model();
m.on('custom', function(model, more) {
     console.log(arguments);
});
m.trigger('custom', m, 'more info');

http://jsfiddle.net/nikoshr/HpwXe/1/

And in a derived model:

var M = Backbone.Model.extend({
    custom: function() {
        this.trigger('custom', this);
    }
});

var m = new M();
m.on('custom', function(model, more) {
     console.log(model);
});
m.custom();

http://jsfiddle.net/nikoshr/HpwXe/2/

like image 149
nikoshr Avatar answered Jan 27 '26 02:01

nikoshr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!