我正在创建一个简单的 Backbone.js 待办事项列表。
在我的 View 初始化中,我有:
var TodoView = Backbone.View.extend({
render: function() {
var html = '<input type="text" value="' + this.model.get('title') + '">';
$(this.el).html(html);
},
initialize: function () {
var thisView = this;
console.log(thisView.model.toJSON()); // <- this works
$(this.el).change(function (thisView) {
console.log(thisView.model.toJSON()); // <- thisView is not View here
thisView.model.set('title', $(this).val());
});
}
});
我也尝试过这个:
setTitle: function () {
console.log(this); // <- this doesn't return View
},
initialize: function () {
$(this.el).change(this.setTitle)
}
最佳答案
Javascript 中的 change
、click
和其他 jQuery“事件”方法的回调仅采用一个参数:触发的事件。
var TodoView = Backbone.View.extend({
render: function() {
var html = '<input type="text" value="' + this.model.get('title') + '">';
$(this.el).html(html);
},
initialize: function () {
var thisView = this;
console.log(thisView.model.toJSON()); // <- this works
$(this.el).change(function (event) {
console.log(thisView.model.toJSON()); // <- this works also
thisView.model.set('title', $(this).val());
});
}
});
但是你不应该这样做。您几乎不应该直接调用 jQuery $
。您应该使用 View 的事件属性。
对于第二部分,您可以执行以下操作:
initialize: function () {
var view = this;
$(this.el).change(function () {
view.setTitle();
});
}
或者这个:
initialize: function () {
var view = this;
// Beware: the first and only argument that setTitle() will receive is the event
$(this.el).change(this.setTitle.bind(this));
}
关于JavaScript 返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762351/