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
Post a Comment