我有一个模型设置默认值如下:
var CampModel = Backbone.Model.extend({
defaults: {
siteID: $.jStorage.get('currentSiteID'),
active: -1,
pending: -1,
},
url: function () {
//some url.
},
sync: function (method, model, options) {
var method = 'read';
var that = this,
options = options || {};
options.success = function(model, response, options){
if(response.errorMessage != "Session is over")
console.log('Update session');
if(response.success)
if(response.returnValue.length){
that.set('response', response.returnValue);
that.CountActiveAndPending(response.returnValue);
}
else {
that.set('response', []);
}
else console.log('report: bad request, error: '+ response.errorMessage);
}
Backbone.sync(method, model, options);
},
},
//Counts active and pending campaigns for front page.
CountActiveAndPending: function (data) {
var active = 0;
var pending = 0;
//var it = this;
$.each(data, function (index, val) {
if (val.ApprovedOnSite) active++;
else pending++;
});
this.set('active', active);
this.set('pending', pending);
}
});
在不同的模型中,我尝试获取模型参数,如下所示:
this.set({
campModel: new CampModel(),
})
});
this.get('campModel').save();
console.log(this.get('campModel').get('active'));
},
一切似乎运行得很好但是当我尝试从CampModel获取“活动”参数时,我得到-1默认值而不是模型中指定的值。有没有想过为什么会这样?
答案 0 :(得分:3)
Model#save
是异步的:
console.log(this.get('campModel').get('active'));
服务器尚未回复,因此从未调用CountActiveAndPending
且active
仍为-1
。尝试在success
回调中记录其值。