[英]BackboneJS: this.$el undefined on other key value function (Backbone.View)
我在 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
)?
正确的实现应该像这样使用events
哈希。
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();
如果由于某种原因#addemployee_button
不在"#addemployee"
,那么事件绑定应该发生在实际包含它的任何视图中。
我已经解决了这个问题,我需要的是在初始化时绑定主干对象。
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
关键字在自定义函数变量中调用主干对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.