I have a code like this in JavaScript:
var addModalView = Backbone.View.extend({
tagName:"div",
el:$("#addemployee"),
showbutton:$("#addemployee_button"),
showbutton_click:function(e) {
this.$el.modal("show"); // this.$el is undefined and not working
},
initialize:function() {
this.showbutton.on("click", this.showbutton_click);
this.$el.modal("show"); // this.$el is defined and working
}
});
myaddModalView = new addModalView();
Why is this.$el
defined and working on initialize but not on other key index (showbutton_click
)?
I already solved the problem all i need is to bind the backbone object on initialize.
var addModalView = Backbone.View.extend({
tagName:"div",
el:$("#addemployee"),
showbutton:$("#addemployee_button"),
showbutton_click:function(e) {
this.$el.modal("show"); // this.$el is now defined and working
},
initialize:function() {
this.showbutton.on("click", this.showbutton_click);
_.bindAll(this, "showbutton_click"); // bind it first on showbutton_click
this.$el.modal("show"); // this.$el is defined and working
}
});
myaddModalView = new addModalView();
This bind code is the solution and should be added on initialize
: _.bindAll(this, "showbutton_click");
so you can call the backbone object inside your custom function variables using the this
keyword.