Cannot access "this" in bind callback in backbone.js app
backbone.js, javascript, jquery
Solution
In JavaScript, `functions` create new context for `this`. And with jQuery, when you bind an events, jQuery assign `this` to the current element. That's why you lost the context. So what can you do?
First, you can manually assign the this value:
this.reference.bind('click', _.bind(this.toggle, this));
Second, the best way is to manage events in the Backbone View `event` object:
Backbone.View.extend({
events: {
"click element": "toggle"
}
// ...rest of your code...
});
Problem
So here is my simple popover module again. It can be assigned to a view which will trigger the popover: ``` function(app) { var Popover = app.module(); Popover.Views.Default = Backbone.View.extend({ className: 'popover', initialize: function() { this.visible = true; this.render(); }, setReference: function(elm) { this.reference = elm; this.reference.bind('click', this.toggle); }, beforeRender: function() { this.content = this.$el.find('.popover'); }, show: function() { //this.visible = true; }, hide: function() { //this.visible = false; }, toggle: function() { this.visible ? this.hide() : this.show(); } }); // Required, return the module for AMD compliance. return Popover; }); ``` This is how I set the popover: ``` Main.Views.Start = Backbone.View.extend({ template: "main/start", serialize: function() { return { model: this.model }; }, initialize: function() { this.listenTo(this.model, "change", this.render); }, beforeRender: function(){ this.popover = new Popover.Views.Default(); this.insertView(this.popover); }, afterRender: function() { this.popover.setReference(this.$el.find('.member')); } }); ``` I want the toggle function of popover to be called when `this.$el.find('.member')` is clicked. This works fine. However inside the toggle function I cannot access "this" from popover object, instead "this" contains the html from its parent. So I get an error in toggle function: ``` TypeError: Object [object HTMLAnchorElement] has no method 'show' ``` Any ideas how to get access to the actuall popover object inside toggle callback?