Knockout Cleavage

My application model looks very big. How to split it into files and namespaces? Create a second namespace object and pass the view model as a parameter?

var BALL = {}; BALL.roll = function(avm) { // function code }; 
+6
source share
1 answer

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; // your myapp.navigation object this.someFunction = function() { } }); 

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.

+11
source

Source: https://habr.com/ru/post/908034/


All Articles