Search code examples
javascripteventsbackbone.jsunderscore.jsbackbone-events

Backbone: Reference events to parent object


I want to replace the Backbone.Events system from some sub object with the one of my parent object. Example:

// initialize function of the repository object
initialize: function() {
        var users = new Backbone.Collection();
        
        // we save a reference of our event system in ourEvents object
        var ourEvents = {};
        ourEvents.on = this.on;
        ourEvents.off = this.off;
        ourEvents.trigger = this.trigger;
        ourEvents.bind = this.bind;
        ourEvents.unbind = this.unbind;

        // now we overwrite events in users.collection with our one
        _.extend(users, ourEvents);

        // now we listen on the test event over this
        this.on('test', function() { alert('yiha'); });

        // but triggering over users works too!
        users.trigger('test');
}

As you we now got some sort of one to many event system. One listener and many object which could fire events.

This helps me when working with different Backbone.Collections or Backbone.Models which got the same view system as front-end.

As you see the solution is not yet optimal.

Is there a shorter way to overwrite the event system ?

UPDATE: So I studied the Backbone Source code and found out that Backbone.Events saves a callback list under: this._callback. This should at least theoretically work:

this.users._callbacks = this._callbacks = {};

Solution

  • Clean Backbone way of doing that would be to bind the events on the collection rather then trying to copy them for some reason from an object

    // initialize function of the repository object
    initialize: function() {
            var users = new Backbone.Collection();
    
            users.on('on', this.on, this);
            users.on('off', this.off, this); // third parameter to set context of method to the current view
            // ...and so on
            // you were listening here on the current view but triggering later on collection - this would never work
            users.trigger('on'); // would call the this.on method in the context of current view
            // if this method would have been triggered from inside of the users collection it would still trigger the desired method inside of this view
    }
    

    A tip - never touch and take advantage of methods and variables preceded with an underscore - these are meant to be private APIs and properties and might change at any point in time with the next release as only public methods/properties are guaranteed not to change between releases. I believe you were trying here a bit to overcomplicate and looking at some of the errors you'v made you've been trying bit too hard and in too many diferent ways :) Always try to keep things simple