Backbone.js:如何处理模型和服务器响应之间的差异
我正在编写一个 Backbone 应用程序,我无法控制服务器返回的实体。
事实证明,拥有与服务器使用的 JSON 略有不同的数据内部表示形式对我来说很方便。从一个方向来看,事情很简单:我可以编写一个 Model.parse() 方法,该方法将服务器返回的 JSON 作为输入并返回对象的属性。
我不太确定在另一个方向上该怎么做。我找不到在序列化对象以进行保存时调用的方法。有 Model.toJSON()
但在保存模型之前似乎没有使用它。
我应该如何处理这种差异?
I am writing a Backbone application, where I have no control over the entities returned by the server.
It turns out that it is convenient for me to have an internal representation of the data which is slightly different with respect to the JSON used by the server. In one direction, things are easy: I can write a Model.parse()
method which takes as input the JSON returned by the server and returns the attributes of my object.
I am not really sure what to do in the other direction. I could not find a method that is called when my object is serialized for saving. There is Model.toJSON()
but it does not seem to be used before the model is saved.
How am I supposed to handle this difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先 - 带注释的来源是查找有关 Backbone 问题答案的最佳位置。
查看 Backbone.sync 的源代码,您可以看到模型是使用 JSON.stringify(model.toJSON()) 序列化的(假设您没有使用
emulateJSON
),因此重写此方法应该可以实现您所需要的。如果没有减少测试用例,我无法解释为什么这对您不起作用。更长的答案是,要完全控制服务器客户端同步,您应该编写自己的 Backbone.sync 实现。该方法相当简单(请参阅带注释的源代码),如果您只想进行简单的更改,则可以简单地包装原始同步。
例如:
要使用自定义同步方法,只需将其声明为模型的一部分
First up - the annotated source is the best place to find answers to questions about Backbone.
Looking at the source for
Backbone.sync
you can see that the model is serialized usingJSON.stringify(model.toJSON())
(presuming you are not usingemulateJSON
) so overriding this method should achieve what you need. I can't explain why this is not working for you without a reduced test case.The longer answer is that to have full-control of server-client synchronisation you should write your own Backbone.sync implementation. The method is fairly simple (see the annotated source) and you can simply wrap the original sync if you just want to make simple changes.
For example:
To use your custom sync method just declare it as part of your model