I have a very large knockout view model that consists of hundreds of other view models that go several levels deep. This view model was getting so large, I had to separate the various view models into their own files. I used requirejs to coalesce all these files for loading. I know next to nothing about requirejs, I'll admit, but it seemed to do the trick. My main,js looks like this:
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)
Very basic stuff, and probably incorrect. So now all of these files are being loaded as global variables, which is bad. What is the best way to get all of these knockout view models, across several files, to be loaded into 1 namespace as a global? Does requirejs offer any functionality for this via define()? Or should I manually change each view model to be defined in this 1 namespace?
Also, can IIFE be leveraged to accomplish what I need?
Thanks!
You should create a module which will be loaded asynchronously and can be cached for your custom model using define and inject wherever you needed.
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);
}); });
Then you can use this one (mod1 and mod2 are dependency for this module ) , this module can be dependency for other module.
For common script you can create app.config file and use name as dependency.
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"
}
} });
and the use as follows.
define(['jquery', 'knockout', 'model'],
function ($, ko, model) {
$(function () {
model.init().always(function () {
ko.applyBindings(model);
});
});
});