Skip to content Skip to sidebar Skip to footer

Backbone - Anyway To Check If An Event Has Been Bound Before?

I'm doing this inside one of my Views: render: function($options) { ... this.collection.on('reset', _(function() { this.render($options); }).bind(this));

Solution 1:

Moving your binding to initialize would be best but assuming that you have good reasons not to, you could just set a flag:

initialize: function() {
    var _this = this;
    this._finish_initializing = _.once(function($options) {
        _this.collection.on('reset', function() {
            _this.render($options);
        });
    });
    //...
},
render: function($options) {
    this._finish_initializing($options);
    //...
}

There are lots of different ways to implement the flag, _.once just nicely hides the flag checking. You could also trigger an event in render have a listener that unbinds itself:

initialize: function() {
    var finish_initializing = function($options) {
        /* your binding goes here ... */this.off('render', finish_initializing);
    };
    this.on('render', finish_initializing, this);
},
render: function($options) {
    this.trigger('render', $options);
    //...
}

That's the same logic really, just dressed up in different clothes. You could also use an explicit flag and an if in render or assign a function to this._finish in initialize and that function would delete this._finish.

Solution 2:

like having Backbone checking if this event has been bound before, or something?

Sure..

!!this.collection._events["render"]

Backbone doesn't expose most of the API required to make it useful. That's alright, use it anyway.

Solution 3:

First, define your event handler function as a named function

varself = this;
var onReset = function() {
    self.render($options);
}

Then, defensively unbind the function each time render is called

this.collection.off('reset', onReset);
this.collection.on('reset', onReset);

Solution 4:

I recently accomplished this using a javascript variable.

Outside of any functions, I declared:

var boundalready =0

Then, inside the function:

if (boundalready == 0){
      boundalready = 1;
      bind(this);
    };

This worked for me pretty well.

Post a Comment for "Backbone - Anyway To Check If An Event Has Been Bound Before?"