javascript - Retaining "this" inside callback function -


i'm not sure if question specific backbone.js. have model following render function:

render: function() {      var self = this;     this.$el.empty();     this.model.fetch({         success: function() {             self.$el.append(self.template(self.model.attributes));               }     });      return this; } 

as can see, inside success callback function, use variable called self. because inside callback, this set window when want set view. there way can retain original reference of this without storing in variable?

is there way can retain original reference of without storing in variable?

yes, reasonable use case proxy method

this.model.fetch({     success: $.proxy(function() {         this.$el.append(this.template(this.model.attributes));           }, this) }); 

alternatively can use underscore's bind method:

this.model.fetch({     success: _.bind(function() {         this.$el.append(this.template(this.model.attributes));           }, this) }); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -