我的 Backbone 模型出现了一些奇怪的行为——我在调用save()
和服务器响应之间设置的属性被丢弃,取而代之的是服务器响应(它只是回显保存的属性)。
这是 Backbone 应该表现的方式吗?当服务器有点滞后时,它让我的应用程序看起来非常疯狂 - 它currentScreen
用旧的属性覆盖我的属性,它向后导航一个屏幕。这是我的代码:
Interview = Backbone.Model.extend({
urlRoot: "/interviews",
defaults: {
"currentScreen": 0
}
});
这是我的 Jasmine/Sinon.JS 测试,描述了我的期望(它失败了Expected 0 to equal 1.
):
describe("Interview model", function() {
beforeEach(function() {
this.interview = new Interview;
});
describe("saving with a slow server response", function() {
beforeEach(function() {
this.server = sinon.fakeServer.create();
});
afterEach(function() {
this.server.restore();
});
it('should not overwrite locally changed attributes on server response', function() {
this.server.respondWith("PUT", "/interviews/1",
[200, { "Content-Type": "application/json" },
'{"id":1,"currentScreen":0}']);
this.interview.set({id: 1, currentScreen: 0});
this.interview.save();
this.interview.set({currentScreen: 1}); // user navigates to next screen
this.server.respond(); // return fake response after currentScreen changed locally
expect(this.interview.get('currentScreen')).toEqual(1);
});
});
});