knockout.js - Knockout dependency injection -


i've seen in great ko manual example of creating new class within self invokation function, in way "should not pollute global namespace". not understand why send myapp (the current namespace) "inner scope", if anyways existed in outer scope. far know, if send object js function, passed ref, change reflected outside of function either. why 'injecting' myapp inside? :

window.myapp = {}; (function (myapp) {     function product() {         var self = this;         self.sku = ko.observable("");         self.description = ko.observable("");         self.price = ko.observable(0.00);         self.cost = ko.observable(0.00);         self.quantity = ko.observable(0);     }     myapp.product = product; }} (window.myapp)); 

thanks !!!

i can think of these reasons scope variable.

  1. let minifiers replace variable shorter name inside function.
  2. keep reference original object if global variable overwritten.
  3. prevent local variables within scope globally accessible, similar 2.

that said, might not issue in simple case.

for example, reason 1:

window.myapp = {}; (function (x) {     function product() {         var self = this;         self.sku = ko.observable("");         self.description = ko.observable("");         self.price = ko.observable(0.00);         self.cost = ko.observable(0.00);         self.quantity = ko.observable(0);     }     x.product = product; }} (window.myapp)); 

for example, reason 2:

window.myapp = {}; (function (myapp) {     myapp.counter = 0;      function product() {         // removed clarity.          myapp.counter++;     }      // code depends on myapp (global) varible.      // break if overwrites global variable.      myapp.product = product; }} (window.myapp));  window.myapp = {}; // break scoped code if wasn't scoped. 

for example, reason 3:

window.myapp = {}; (function (myapp) {     var counter = 0;      function product() {         // removed clarity.          counter++;     }      myapp.product = product; }} (window.myapp)); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -