My personal preference is not to split my applyBindings
calls and instead work with a single global namespace branch.
My reasoning is that in order for multiple bindings to work correctly and not conflict, you need to be very careful that the selected dom target elements do not change. Unfortunately, markup has an unpleasant habit of changing over time, which may cause you problems with your views in the future.
My general approach, which I used in a very large KO project, was
- One global top-level namespace for the entire application, for example
myapp
- Separate individual function blocks into separate files. Usually with their own namespace. e.g. `Myapp.navigation '
- If one namespace, in particular, becomes too large, split it into additional namespaces or if it does not fit, split the same namespace into several files.
- Write all the files at the end to maintain performance.
Some namespace code that I recently used
var Namespace = (function() { var namespace, global, root; namespace = function(identifier, contents) { if (!identifier || identifier.length == 0) { throw Error("A namespace identifier must be supplied"); } global = window; // create the namespace var parts = identifier.split("."); for (var i = 0; i < parts.length; i += 1) { if (!global[parts[i]]) { global[parts[i]] = {}; } if (i == 0) { root = global[parts[i]]; } global = global[parts[i]]; } // assign contents and bind if (contents) { global.$root = root; contents.call(global); } }; return namespace; })();
So in your myapp.navigation file you will have
Namespace("myapp.navigation", function() { var self = this;
This is simply a shorthand for using the self invoking function to pass to a manually-created namespace. This gives you a closed close, and you can use multiple namespace calls with the same namespace in another js file.
Now your call to applyBindings could be
ko.applyBindings(myapp);
Hope this helps.
source share