我正在構建一個複雜的Web應用程序,爲了保持簡單,我在各種文件中創建了各種模塊(對象)。這些模塊可以在某些頁面上需要,而不是在其他頁面上。如何加載關於當前頁面的特定代碼?
因此,我想避免加載任何頁面的所有模塊,增加無用請求的數量。
到目前爲止,我的工作是這樣的:
- 我包括所有需要庫
- 在那之後,我舉例說明這些librairies在
jQuery(function() {});
與細節#ids或.classes論點,目前 頁
一切工作正常,但由於我的應用程序越來越容易,我想用RequireJS管理我的JS。
而這正是事情開始有點令我困惑的地方。
我知道在需要時我可以載入我的模塊,採用require(['module1', 'module2', 'etc'], function (module1, module2, etc) {})
,但我怎麼能說:
「這個頁面上,你加載這些模塊,並與#ids和.classes實例化它們」
和
「這個其他頁面上,你只加載該模塊,與此#其他-ID」
?
模塊1將,例如,從API加載數據,並把它們列出來給定的參數特定表:
// in page 1
var mod1 = new Module1($('#content>table');
mod1.init(); // will load the data from the api with the url located at <table data-api-url="http://....">
// in page 2
var mod1 = new Module1($('#content .items>table'); // The table where we want the data to be populated is not at the same position!
mod1.init();
這意味着,根據不同的頁面上,我必須加載我模塊不同。這就是我不知道如何使用RequireJs:/
感謝您的幫助!
@Cyrilñ不知道我是否明白你想要什麼。你能舉一個你期望的要求爲你做什麼的例子嗎?因爲module1自己會負責用#ids和.classes等來實例化這些庫。這些庫也是模塊。 – devundef 2012-08-01 11:23:10
我回答了有關requirejs和多頁面應用程序的問題,可能有幫助:http://stackoverflow.com/questions/11674824/how-to-use-requirejs-build-profile-r-js-in-a-mult- page-project/11730147#11730147 – devundef 2012-08-01 11:25:15
@devundef添加'data-start'屬性的想法非常有趣,同時也解決了我相信的問題!謝謝:) – 2012-08-01 11:57:24