![](/img/trans.png)
[英]Django templates seems that is not loading Backbone.js in correct order
[英]backbone.js All the templates are loading by default
我的項目與Backbone.js示例應用程序幾乎相似
但是,我的應用程序默認下載所有模板('text!templates / projects / list.html')。 這個對嗎 ?
我的印象是,除非你調用路由器導航列表中的特定項目,否則它將不會加載視圖,集合和模板文件。 我在同一頁嗎?
例如,如果我路由“sample.com/users”,它應該只加載與此“用戶”路由器規范關聯的集合和視圖。 如果我錯了,請糾正我。
拉賈K.
RequireJS的工作原理是定義所有模塊的依賴關系。 由於main.js
在執行任何其他操作之前需要app
,因此它將首先加載app
依賴的所有文件。 由於app
需要router
,而router
需要ProjectListView
,而ProjectListView
需要基於文本的模板,所有這些文件都會在發生任何事情之前加載; RequireJS首先確保define(...)
或require(...)
函數中的每個回調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,因此它也只是為了分離大型應用程序的不同組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.