抱歉,如果这是基本的,但我是 Backbone.js 的初学者,我不知道如何简单地使用从获取的数据分配属性(数据)。我相信这与绑定(bind)(this)有关,但我无法弄清楚。这是我的代码:
var form_model = Backbone.Model.extend({
urlRoot: QuoteForm.ajaxurl,
data: "",
initialize: function()
{
this.fetch({
data: { action: 'quote_form_data' },
success: function (response) {
// this bit won't assign
this.data = response.toJSON();
}
});
}
});
当我使用 console.log() 返回的数据时,它是正确的,但是我无法分配它并在我的 View 中使用数据属性。请帮忙。
最佳答案
编辑:不绑定(bind),成功回调中的this指针指向window对象
var form_model = Backbone.Model.extend({
urlRoot: QuoteForm.ajaxurl,
data: "",
initialize: function()
{
this.fetch({
data: { action: 'quote_form_data' },
success: function (response) {
// this bit won't assign
this.data = response.toJSON();
}.bind(this)
});
}
});
绑定(bind)到 this 将正确设置 this 指针, native .bind 方法仅适用于 EMCAScript 5 及更高版本的浏览器。由于 Backbone 依赖于 Underscore JS,您可以这样做以获得额外的兼容性
var form_model = Backbone.Model.extend({
urlRoot: QuoteForm.ajaxurl,
data: "",
initialize: function()
{
this.fetch({
data: { action: 'quote_form_data' },
success: _.bind(function (response) {
// this bit won't assign
this.data = response.toJSON();
}, this)
});
}
});
关于javascript - Backbone JS : Assign a model attribute in fetch call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24826888/