jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.29k stars 5.53k forks source link

_.after: a problem of context #1665

Closed infacq closed 10 years ago

infacq commented 10 years ago

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.

megawac commented 10 years ago

Bind render to the view instance http://underscorejs.org/#bind

var sempurna = _.after(array_obj.length, _.bind(this.render, this))
infacq commented 10 years ago

thanks @megawac . If you dont mind, the this.render seems would not run the if condition set in the template. Do you have any idea?

megawac commented 10 years ago

@infacq I don't understand the question, ping me on irc (I'm in #documentcloud on freenode) and I'll see if I can help you

megawac commented 10 years ago

On another note, would it be worth changing the accepted parameters for _.after (similarly for _.defer, etc) to

function(n, callback, context) {
  callback = createCallback(callback, context);
  //...
}