问题
See Data dependency in module
I have a few modules in my app which depend on data coming from the server. I implemented the modules as IIFEs, as the module pattern suggests, but in order to be able to reference them as the callback for the ajax request I am thinking of defining them as regular functions, and initialising them in the callback (see the answer in the other post for reference). Everywhere I looked, the module pattern consisted of IIFEs. What are the drawbacks(if any) of using them as regular functions which I instantiate in the AJAX callback? Is that a good practice?
回答1:
Have a look at following example from previous post:
getAJAX(url, function(data){
// write any code that want data from Ajax.
}, true);
This code contains IIFE function call. Here it is called an
anonymous
function also. It is a way of invoking inline function and has nothing to do with Modular approach.
See following Class representation in javascript:
var ClassName = function(data, pubsubService) {
var items = [];
// public function
this.generateItems = function(firstItemIndex, stopIndex) {
var dataLength = data.length;
stopIndex = (stopIndex < dataLength) ? stopIndex : dataLength;
items = data.slice(firstItemIndex, stopIndex);
pubsubService.publish('itemsGenerated');
};
// private function
var getItems = function() {
return items;
};
return {
generateItems : generateItems,
getItems : getItems
};
};
This is a class where
generateItems
is a public function andgetItems
is a private function.
Now in reference to you previous post, instead of creating regular function create a class as module
which contains method of that module, create object
and call methods like following:
Var obj = new ClassName(data,pubsubService);
obj.generateItems(firstItemIndex,stopIndex);
I think this can help you understand the concept.
Refer following link to explore more:
http://book.mixu.net/node/ch6.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=5m_t2A6hozg
来源:https://stackoverflow.com/questions/31492081/modules-that-are-not-iifes