javascript 初始backbone.js 数据获取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5494306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initial backbone.js data fetch
提问by Webster
I've been playing with backbone.js for the last few days, editing the Todos example and writing my own version.
最近几天我一直在使用backbone.js,编辑Todos示例并编写我自己的版本。
I'm now looking at creating a controller with multiple routes, but what I have found after following the Todos example is calling the Todos.fetch()
, causes the items to be re-rendered. I think its calling the refresh event?
我现在正在考虑创建一个具有多个路由的控制器,但是在遵循 Todos 示例之后我发现调用Todos.fetch()
, 会导致重新渲染项目。我认为它调用了刷新事件?
The backbone.js documentation says:
Backbone.js 文档说:
Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped into place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.
请注意,不应使用 fetch 在页面加载时填充集合——加载时所需的所有模型都应该已经引导到位。fetch 旨在为不需要立即使用的接口延迟加载模型:例如,可以切换打开和关闭的笔记集合的文档。
What is the best way to load data then? Can I use an use an ajax call to get the data and pass it when instantiating the main controller?
What about if I were to change page and a new view were to shown? Would I just call the fetch()
function?
那么加载数据的最佳方式是什么?我可以使用 ajax 调用来获取数据并在实例化主控制器时传递它吗?如果我要更改页面并显示新视图怎么办?我只是调用fetch()
函数吗?
采纳答案by Julien
This bit of documentation is there to remind you that you should load all the data on the initial page load and use fetch for all the subsequent loads.
这段文档是为了提醒您,您应该在初始页面加载时加载所有数据,并在所有后续加载中使用 fetch。
You can have code like this:
你可以有这样的代码:
MyCollection = new Collection({some json data});
Much faster than a page load then a couple of request to load the data.
比页面加载快得多,然后是几个加载数据的请求。
回答by Vlad Gurovich
Im a bit confused on the wording of the doc as well, but fetch is the way to tell your Collectionor Modelto go the server and get the data via either your own sync function or Backbone.syncwhich already internally uses ajax and can pass the result along to your success or error function.
我对文档的措辞也有点困惑,但 fetch 是告诉你的Collection或Model去服务器并通过你自己的同步函数或Backbone.sync获取数据的方式,它已经在内部使用了 ajax 并且可以通过结果与您的成功或错误功能有关。
As far as Todos example you mentioned, thats how Collectionis meant to work. It updates the models, then triggers 'refresh' event which may force your view to be re-rendered, like you said.
就您提到的 Todos 示例而言,这就是Collection 的工作方式。它更新模型,然后触发 'refresh' 事件,这可能会强制您的视图重新呈现,就像您说的那样。
I highly recommend looking at Backbone.js code. Its very effectively documented and the flow of events and method calls is very easy to grasp due to that.
我强烈建议查看 Backbone.js 代码。它的文档非常有效,因此事件和方法调用的流程很容易掌握。