`

A JavaScript Module Pattern

    博客分类:
  • Ext
阅读更多

Global variables are evil. Within YUI, we use only two globals: YAHOO and YAHOO_config. Everthing in YUI makes use of members within the YAHOO object hierarchy or variables that are scoped to such a member. We advise that you exercise similar discipline in your own applications, too.

Douglas Crockford has been teaching a useful singleton pattern for achieving this discipline, and I thought his pattern might be of interest to those of you building on top of YUI. Douglas calls this the “module pattern.” Here’s how it works:

1. Create a namespace object: If you’re using YUI, you can use the YAHOO.namespace() method:

YAHOO.namespace("myProject");

This assigns an empty object myProject as a member of YAHOO (but doesn’t overwrite myProject if it already exists). Now we can begin adding members to YAHOO.myProject.

2. Assign the return value of an anonymous function to your namespace object:

YAHOO.myProject.myModule = function () {

return {
myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty.";
myPublicMethod: function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
}
};

}(); // the parens here cause the anonymous function to execute and return

Note the very last line with the closing curly brace and then the parentheses () — this notation causes the anonymous function to execute immediately, returning the object containing myPublicProperty and myPublicMethod. As soon as the anonymous function returns, that returned object is addressable as YAHOO.myProject.myModule.

3. Add “private” methods and variables in the anonymous function prior to the return statement. So far, the above code hasn’t bought us any more than we could have gotten by assigning myPublicProperty and myPublicMethod directly to YAHOO.myProject.myModule. But the pattern does provide added utility when we place code before the return statement:

YAHOO.myProject.myModule = function () {

//"private" variables:
var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";

//"private" method:
var myPrivateMethod = function () {
YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
}

return {
myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
myPublicMethod: function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");

//Within myProject, I can access "private" vars and methods:
YAHOO.log(myPrivateVar);
YAHOO.log(myPrivateMethod());

//The native scope of myPublicMethod is myProject; we can
//access public members using "this":
YAHOO.log(this.myPublicProperty);
}
};

}(); // the parens here cause the anonymous function to execute and return

In the codeblock above, we’re returning from an anonymous function an object with two members. These members are addressable from within YAHOO.myProject.myModule as this.myPublicProperty and this.myPublicMethod respectively. From outside of YAHOO.myProject.myModule, these public members are addressable as YAHOO.myProject.myModule.myPublicProperty and YAHOO.myProject.myModule.myPublicMethod.

The private variables myPrivateProperty and myPrivateMethod can only be accessed from within the anonymous function itself or from within a member of the returned object. They are preserved, despite the immediate execution and termination of the anonymous function, through the power of closure — the principle by which variables local to a function are retained after the function has returned. As long as YAHOO.myProject.myModule needs them, our two private variables will not be destroyed.

4. Do something useful with the pattern. Let’s look at a common use case for the module pattern. Suppose you have a list, some of whose list items should be draggable. The draggable items have the CSS class draggable applied to them.


 
  1. <!--This script file includes all of the YUI utilities:-->  
  2. <script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/utilities/utilities.js"></script>  
  3.   
  4. <ul id="myList">  
  5.     <li class="draggable">Item one.</li>  
  6.     <li>Item two.</li> <!--item two won't be draggable-->  
  7.     <li class="draggable">Item three.</li>  
  8. </ul>  
  9.   
  10. <script>  
  11. YAHOO.namespace("myProject");  
  12. YAHOO.myProject.myModule = function () {  
  13.   
  14.     //private shorthand references to YUI utilities:  
  15.     var yue = YAHOO.util.Event,  
  16.         yud = YAHOO.util.Dom;  
  17.   
  18.     //private method:  
  19.     var getListItems = function () {  
  20.   
  21.         //note that we can use other private variables here, including  
  22.         //our "yud" shorthand to YAHOO.util.Dom:  
  23.         var elList = yud.get("myList");  
  24.         var aListItems = yud.getElementsByClassName(  
  25.             "draggable"//get only items with css class "draggable"  
  26.             "li"//only return list items  
  27.             elList //restrict search to children of this element  
  28.         );  
  29.         return aListItems;  
  30.     };  
  31.   
  32.     //the returned object here will become YAHOO.myProject.myModule:  
  33.     return  {  
  34.   
  35.         aDragObjects: [], //a publicly accessible place to store our DD objects  
  36.   
  37.         init: function () {  
  38.             //we'll defer making list items draggable until the DOM is fully loaded:  
  39.             yue.onDOMReady(this.makeLIsDraggable, thistrue);  
  40.         },  
  41.   
  42.         makeLIsDraggable: function () {  
  43.             var aListItems = getListItems(); //these are the elements we'll make draggable  
  44.             for (var i=0, j=aListItems.length; i<j; i++) {  
  45.                 this.aDragObjects.push(new YAHOO.util.DD(aListItems[i]));  
  46.             }  
  47.         }  
  48.   
  49.     };  
  50. }(); // the parens here cause the anonymous function to execute and return  
  51.   
  52. //The above code has already executed, so we can access the init  
  53. //method immediately:  
  54. YAHOO.myProject.myModule.init();  
  55. </script>  


This example is a simple one, and it’s deliberately verbose — if this was all we were doing, we could doubtless write it in a more compact way. However, this pattern scales well as the project becomes more complex and as its API grows. It stays out of the global namespace, provides publicly addressable API methods, and supports protected or “private” data and methods along the way.

分享到:
评论

相关推荐

    module-pattern-javascript

    模块模式 Javascript介绍这个项目只是为了测试模块模式javascript要求安装$ git clone git@github.com:kiki-le-singe/module-pattern-javascript.git $ bower install包含的 JavaScript 库来源

    js-module-pattern-test

    js-module-pattern-test 这是 MakerSquare 作为学习 AJAX 的工具给出的。 因为我已经有了 AJAX 的经验,所以我借此机会学习和使用了 JavaScript 模块模式。 共有三个模块。 显示、电影和 API。 显示和 API 功能如...

    Learning JavaScript Design Patterns - Addy Osmani.pdf

    Use several options for writing modular code—including the Module pattern, Asyncronous Module Definition (AMD), and CommonJS Discover design patterns implemented in the jQuery library Learn popular ...

    Programming JavaScript Applications

    Prototypal Inheritance, Prototype Cloning and the Flyweight Pattern, The Module Pattern, Unit Testing, Coming soon:, Architecting for Scale, Collaboration, Build, Continuous Integration, Deployment, ...

    Modular Programming with JavaScript(PACKT,2016)

    Even JavaScript developers are now interested in building programs in a modular pattern. Modules help people who aren’t yet familiar with code to find what they are looking for and also makes it ...

    data-module-pattern-prototype:一个尝试使用data- *属性将原始HTML与Javascript绑定以创建动态行为的小项目

    数据模块模式项目 一个尝试使用data- *属性将原始HTML与Javascript绑定以创建动态... Return a cleanup function that will be used to remove any code that must be cleaned up, i.e., event listeners. */ return

    module-pattern-[removed]javascript中的模块化模式发布

    模块化模式在javascript世界中,有许多编程工具,唯一的细节就是滥用其工具。 最后,您将获得分布在整个代码中且没有顺序的变量和函数,这最终是无法维护的。 编写代码时的最佳实践之一是使用javascript中的设计模式...

    JavaScript学习之二 — JavaScript创建对象的8种方式

    6. **模块模式(Module Pattern)** 这种模式结合了私有变量和公共接口,提供了封装和隐藏实现细节的能力。 ```javascript var person = (function() { var _name = 'Eve'; var _age = 28; function sayHello...

    即用即查JavaScript核心对象参考手册:JavaScript

    正则表达式用于模式匹配和文本操作,`/pattern/flags`定义正则,`test()`检查匹配,`exec()`执行搜索并返回结果数组,`match()`、`search()`、`replace()`、`split()`在字符串中应用正则表达式。 8. **数学Math**...

    外文翻译:学用JavaScript设计模式

    - **Composite Pattern(组合模式)**:将对象组合成树形结构以表示部分-整体层次结构。 - **适配器模式**:允许不兼容的接口之间可以协同工作。 - **观察者模式**:在对象之间定义一对多的依赖关系,当一个对象的...

    Pro.JavaScript.Design.Patterns.2008

    3. revealing module pattern:暴露模块内部变量和函数的一种方式,提高代码组织性和可维护性。 4. 工厂函数与类模式:在没有类的JavaScript中,模拟面向对象编程。 5. 动态代理模式:通过Proxy对象实现对目标对象的...

    data-module-pattern-demo:Viget使用的数据模块模式的快速演示

    数据模块模式(Data Module Pattern)是一种在JavaScript应用中组织代码的方式,它强调将数据与处理数据的逻辑分离,以提高代码的可维护性和可重用性。在这个名为"data-module-pattern-demo"的项目中,Viget公司提供...

    jQuery Design Patterns

    1. **模块化编程**:书中会介绍如何使用命名空间、立即执行函数表达式(IIFE)以及AMD(Asynchronous Module Definition)和CommonJS模块加载机制来组织代码,避免全局变量污染,提高代码的可复用性和可测试性。...

    javascript创建对象的方式(一)

    5. **模块模式(Module Pattern)**: 模块模式是JavaScript中的一种设计模式,它允许我们创建私有变量和方法,同时提供公共接口。 ```javascript var PersonModule = (function() { var name = "John", age = ...

    bootstrap_module_pattern_tracalorie:一个使用模块模式存储膳食和卡路里的JS应用

    $ cd js_module_pattern_tracalorie 用法 有4个控制器(模块)可以创建此应用程序: 为了与本地存储进行通信,添加,编辑,删除项StorageCtrl控制器 用于控制膳食及其卡路里的ItemCtrl控制器 用于操纵UI UICtrl控制...

    DesignPattern:JavaScript的设计模式

    var Module = (function() { var privateVar = 'private'; function privateMethod() {} var publicVar = 'public'; function publicMethod() {} return { publicVar: publicVar, publicMethod: public...

    【JavaScript源代码】js实现中文转拼音的完整步骤记录.docx

    1. **ES Module 方式** ```javascript import { pinyin } from 'pinyin-pro'; const result = pinyin('汉语拼音'); // 'hànyǔpīnyīn' ``` 2. **CommonJS 方式** ```javascript const { pinyin } = ...

Global site tag (gtag.js) - Google Analytics