很抱歉,如果这是基本的,但我是Backbone.js的总启动者,我无法解决如何简单地为从fetch获取的数据分配属性(数据)。我相信它与绑定(这个)有关,但我无法弄明白。这是我的代码:
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()时返回的数据是正确的,但是我无法分配它并在我的视图中使用data属性。请帮忙。
答案 0 :(得分:1)
编辑:没有绑定,成功回调中的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();
}.bind(this)
});
}
});
绑定到此将正确设置此指针,本机.bind方法仅适用于EMCAScript 5及更高版本的浏览器。由于主干取决于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)
});
}
});
答案 1 :(得分:1)
更多读者友好版本
var form_model = Backbone.Model.extend({
urlRoot: QuoteForm.ajaxurl,
data: "",
initialize: function () {
var _this = this;
this.fetch({
data: { action: 'quote_form_data' },
success: function (response) {
// more reader freindly version would be;
_this.data = response.toJSON();
}
});
}
});