我的项目与此Backbone.js Sample Application几乎相似
但是,我的应用程序默认下载所有模板
(' text!templates / projects / list.html')。这是对的吗?
我的印象是,除非你调用 路由器导航列表中的特定项目,它不会加载视图,集合和模板文件。我在同一页吗?
例如,如果我路由" sample.com/users" ;,它应该只加载与此" user"相关的集合和视图。路由器规范。如果我错了,请纠正我。
Raja K
答案 0 :(得分:0)
RequireJS通过定义所有模块的依赖关系来工作。由于main.js
在执行任何其他操作之前需要app
,因此它将首先加载app
所依赖的所有文件。由于app
需要router
,而router
需要ProjectListView
,而ProjectListView
需要基于文本的模板,所以这些文件都会在之前加载 / em>发生任何事情; RequireJS首先确保define(...)
或require(...)
函数中的每个回调都具有所需的回调。这是预期的。
如果要在实际创建视图之前推迟加载文件,则可以采用不同的方式构建View。它使事情变得相当复杂,这就是大多数人不这样做的原因。
以下是样本应用中ProjectListView
的一个选项。它使用When JS提供Promise来处理模板的异步加载。这具有使render
函数异步的不幸副作用,因为它可能需要等待模板文件显示。仍然....
define([
'jquery',
'underscore',
'backbone',
'when'
], function($, _, Backbone, when){
var ProjectListView = Backbone.View.extend({
el: $('#container'),
initialize: function() {
// Load the template file upon the creation of the view
this._ensureTemplateLoaded();
},
// This returns a Promise that will be resolved after the
// template file is loaded.
_ensureTemplateLoaded: function() {
var self = this;
return when.promise(function(resolve) {
// Require in the template. Note that this is
// a no-op if the template has been loaded previously
require([
'text!templates/project/list.html'
], function(projectListTemplate) {
// Resolve our promise, providing the template
resolve(projectListTemplate);
});
});
},
render: function(){
// Wait for the promise to be resolved to make sure
// we have loaded the template before attempting to render
var self = this;
this._ensureTemplateLoaded().then(function(projectListTemplate) {
// Huzzah! Now we can do the regular rendering with the
// template provided by the Promise
var data = {};
var compiledTemplate = _.template( projectListTemplate, data );
// Append our compiled template to this Views "el"
self.$el.append( compiledTemplate );
});
}
});
// Our module now returns our view
return ProjectListView;
});
如上所述,它有点复杂。除非您正在加载大量文件,否则对最终用户的好处非常小。
最后,请注意,RequireJS的优化器r.js
可以通过构建多个完全组装的JS模块(即目标模块及其所有依赖项)来有效地完成同样的事情。这通常意味着客户端将多次下载相同的JS,因此它也只是为了分离大型应用程序的不同组件。