在页面加载时 bootstrap 放置 Backbone 模型的方法

Methods to bootstrap in place Backbone models on page load

对于 "Fetch",Backbone 文档说:

Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to 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.

因为我的所有数据都保存在数据库中,所以当我的应用程序加载后我做的第一件事就是获取我需要的集合。也许我只是误会了,但我怎么能在不获取的情况下展示任何模型呢?文档中 "should already be bootstrapped in to place." 是什么意思?

自举数据是通常使用 XHR 获取的数据,但已作为序列化字符串嵌入到 HTML 中,以避免 XHR 调用,从而优化初始页面加载。您仍然需要从服务器端的数据库中检索它以便嵌入它,但有时总体而言,由于感知、缓存等各种因素,这会导致更快的页面加载。

在我的应用程序中,我无论如何都使用了 fetch,但覆盖了 Backbone.sync(),以便 fetch() 将首先检查任何 bootstrapped 数据。

<div class="bootstrap" data-json="...JSON data here..." data-url="/foo"></div>

然后 /foo 的抓取将 return bootstrapped 数据(如果存在),否则回退到通过网络加载。一旦使用该 bootstrap 元素,它将删除该元素,以便后续提取将使用网络。

这样我的客户端加载逻辑就可以保持简单并且不关心任何加载和 bootstrapping 问题。