2017-01-25 53 views
0

我有一個非常大的淘汰賽視圖模型,其中包含數百個其他視圖模型,其中有幾個級別深。這個視圖模型變得如此之大,我不得不將各種視圖模型分離到他們自己的文件中。我使用requirejs來合併所有這些文件進行加載。我幾乎不知道requirejs,我承認,但它似乎有訣竅。我的主,js看起來像這樣:跨多個文件的淘汰賽視圖模型

requirejs(
["Scripts/ViewModel/Shipment/consts.js", 
"Scripts/ViewModel/Shipment/utils.js", 
"Scripts/ViewModel/Shipment/functions.js", 

"Scripts/ViewModel/Shipment/OptionListItemVM.js", 
"Scripts/ViewModel/Shipment/OptionsVM.js", 
"Scripts/ViewModel/Shipment/ShipmentOptionsVM.js", 
"Scripts/ViewModel/Shipment/PackOptionsVM.js", .... (and so on) 

非常基本的東西,可能不正確。所以現在所有這些文件都被加載爲全局變量,這是不好的。在幾個文件中獲得所有這些挖空視圖模型的最佳方式是作爲全局文件加載到1個命名空間中? requirejs是否通過define()提供了這個功能?或者我應該手動更改每個視圖模型以在這個1命名空間中定義?

另外,IIFE可以用來完成我所需要的嗎?

謝謝!

回答

0

您應該創建一個模塊,該模塊將被異步加載,並且可以使用define和inject在需要的地方爲您的自定義模型進行緩存。

define(['module1', 'module2'], function (mod1, mod2) { 
$('#btn').click(function() { 
    mod1.runJob(mod2.url, 'complete', 5000, 20000); 
}); 

$('#btn2').click(function() { 
    mod2.runJob(mod2.url, 'complete2', 5000, 20000); 
}); }); 

然後你可以使用這個(MOD1和MOD2是這個模塊依賴),該模塊可以爲其它模塊依賴。

對於通用腳本,您可以創建app.config文件並使用名稱作爲依賴項。

requirejs.config({ 
paths: { 
    "jquery": "jquery-1.10.2", 
    "jquery-ui": "jquery-ui-1.11.4", 
    "General": "General", 
    "knockout": "knockout-3.4.0.debug", 
    "komapping": "knockout.mapping-latest.debug", 
    "modernizr": "modernizr-2.8.3", 
    "respond": "respond", 
    "underscore": "underscore", 
    "datatable": "DataTables/jquery.dataTables", 
    "bootstrap": "bootstrap", 
    "bootstrap-dialog": "bootstrap-dialog", 
    "bootstrap-datepicker": "bootstrap-datepicker" 
}, 
shim: { 
    "jquery.appender": ["jquery"], 
    "jquery.textReplacer": ["jquery"], 
    "jquery-ui": { 
     "deps": ["jquery"], 
     "exports": "$" 
    }, 
    "bootstrap-responsive": { 
     "deps": ["bootstrap", "respond"], 
     "exports": "bootstrap-responsive" 
    }, 
    "komapping": { 
     "deps": ["knockout"], 
     "exports": "komapping" 
    }, 
    "bootstrap": { 
     "deps": ["jquery"], 
     "exports": "bootstrap" 
    }, 
    "bootstrap-dialog": { 
     "deps": ["bootstrap", "jquery"], 
     "exports": "bootstrap-dialog" 
    } 
} }); 

和使用方法如下。

define(['jquery', 'knockout', 'model'], 
function ($, ko, model) { 
    $(function() { 
     model.init().always(function() { 
      ko.applyBindings(model); 
     }); 
    }); 
});