Search code examples
backbone.jsunderscore.js

_.after: a confuse with context


I have extend this function inside Backbone.view

toggle: function () {
   var sempurna = _.after(array_obj.length, this.render);
   _.each(array_obj, function (v,k) {
      v.perormSomething();
      delete array_obj[key];
      sempurna();
  }, this);
}

And so I thought that I could render the view straight away the loop is completed. But somehow the this keyword is refering to window instead of the view. How do I point to the intended this to view.


Solution

  • The this is set to window because your are calling sempurna() without the dot notation (so without any explicit receiving object).

    To fix this you need to _.bind (or use the browser native bind if available) your sempurna to this:

    toggle: function () {
       var sempurna = _.bind(_.after(array_obj.length, this.render), this);
       _.each(array_obj, function (v,k) {
          v.perormSomething();
          delete array_obj[key];
          sempurna();
      }, this);
    }
    

    Demo JSFiddle.