Backbone.js 模型数据检索
一般问题,如果我调用 Web 服务来返回与我的 Backbone 模型之一相关的数据。是从模型本身内部调用 Web 服务更好,还是应该在初始化时将 WS 的结果传递给模型。
我倾向于将 WS 调用合并到我的模型中,但显然可能会遇到延迟问题。
那么处理这种数据检索的最佳位置在哪里呢?
General question if I am calling a webservice to return data related to one of my Backbone models. Would it be better to call the webservice from within the model itself or should I pass in the results of the WS to the model on initialization.
I'm leaning towards incorporating the WS call within my model but then obviously may run into latency issues.
So where is the best place to handle this data retrieval?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果渲染 HTML 的页面已经知道将进入模型的数据,我绝对更喜欢将数据直接渲染到模型构造函数中。像这样的东西(假设有一个 Rails 视图,但这只是为了说明目的):
假设您的控制器已将一些 JSON 数据呈现为
@modelData
。通过这种方式,您可以立即获得数据,而不需要第二次回调服务。我已经多次使用这种方法并取得了很大的成功。
编辑
对此进行扩展,这会减少对服务器的调用,因为后端正在以 HTML 或 JS 形式呈现返回到客户端的数据。上述代码的结果(在视图渲染之后)可能是这样的:
但是,如果您采用另一种方式,则会对服务器进行两次调用:
对服务器的第一个调用是返回代码的调用。当您调用 fetch 时,会发生第二种情况。
如果您问的是其他问题,那么我深表歉意。您可能会澄清“处理这些呼叫的最佳位置在哪里”的含义。
If the page that is rendering your HTML already knows the data that will go into your model, I definitely prefer rendering the data right into the model constructor. Something like this (assuming a Rails view, but that is just for the purpose of illustration):
Let's assume your controller has rendered some JSON data as
@modelData
.Doing it this way allows you to have your data immediately and not require a second call back to the service. I have used this approach several times with a lot of success.
Edit
To expand on this, this results in fewer calls to the server because the back end is rendering the data in the HTML or JS that gets returned to the client. The result (after view rendering) of the above code might be something like this:
If you to it the other way, however, you make two calls to the server:
The first call to the server is the one returning your code. The second happens when you call fetch.
If you are asking something else, then I apologize. You might clarify what you mean by "where is the best place to handle these calls".
正确的方法是先创建模型,然后使用 model.fetch 来提取数据。这样您的所有 ajax 逻辑都会整合到 Backbone.sync 中。
如果您在渲染 HTML 时有可用的数据,我会将其放入缓存中,例如
sessionStorage
,并且让您的同步代码能够读取/写入缓存。这样,如果您需要将 Web 服务调用移出 HTML 渲染(例如,如果您使用应用程序缓存),则无需进行重大重构。The right way to do this is to create the model first and then use
model.fetch
to pull the data. That way all your ajax logic is consolidated inBackbone.sync
.If you have the data readily available at the time you render the HTML, I would place it into a cache, for example
sessionStorage
, and have your syncing code able to read from/write to the cache. That way if you ever need to move the web service call out of the HTML rendering (e.g., if you're using an application cache), you don't need to do a major refactoring.