在其他键值函数中未定义this.$el
的问题可能是因为上下文的问题,可以通过使用箭头函数或使用bind()
方法来解决。以下是两种解决方法的代码示例:
var MyView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'otherFunction');
},
render: function() {
this.$el.html('Hello World');
return this;
},
otherFunction: () => {
this.$el.addClass('active'); // 使用箭头函数保留了正确的上下文
}
});
bind()
方法:var MyView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'otherFunction');
},
render: function() {
this.$el.html('Hello World');
return this;
},
otherFunction: function() {
this.$el.addClass('active');
}.bind(this) // 使用bind()方法将上下文绑定到函数中
});
以上两种方法都可以确保this.$el
在其他键值函数中被正确定义。