Reputation: 652
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
)?
Upvotes: 1
Views: 70
Reputation: 43156
The proper implementation should be like this using the events
hash.
var addModalView = Backbone.View.extend({
el: $("#addemployee"), // should be avoided if possible
events: {
'click #addemployee_button': 'showbutton_click'
},
initialize: function() {
this.$el.modal("show");
},
showbutton_click: function(e) {
this.$el.modal("show");
},
});
myaddModalView = new addModalView();
If for some reason #addemployee_button
is not inside "#addemployee"
, then the event binding should happen in whichever view actually contains it.
Upvotes: 1
Reputation: 652
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.
Upvotes: 0