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
)?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.