我在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();
为什么定义this.$el
并在初始化时起作用,但不能在其他键索引(showbutton_click
)上起作用?
我已经解决了所有我需要在初始化时绑定主干对象的问题。
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();
此绑定代码是解决方案,应将其添加到initialize
:_.bindAll(this, "showbutton_click");
上,以便您可以使用this
关键字在自定义函数变量内调用主干对象。