A JavaScript module pattern-a component mode of JavaScript

Source: Internet
Author: User
Source: http://yuiblog.com/blog/2007/06/12/module-pattern/
Translation: Frank
Global variables are a curse. In Yui, we only use two global variables Yahoo and yahoo_config. All Yui objects access members or variables belonging to this member from the Yahoo object level. We recommend that you follow this practice in your program.
Douglas crockford has taught us how to use singletion pattern to implement this mode, and I think it is interesting to apply it to build a Yui-based model. Douglas calls this "" to see how he did it?

1,Create a namespace object: If you use Yui, you can use the Yahoo. namespace () method:

JS Code
 
 
  1. Yahoo. namespace ("myproject ");


This assigns an empty myproject object, which is a member of Yahoo (but does not overwrite myproject if it already exists ). Now we can join the Yahoo. myproject member.

 

2,Returns a value from an anonymous function and assigns it to a namespace object.

JS Code
  1. Yahoo. myproject. mymodule = function (){
  2. Return {
  3. Mypublicproperty: "I'm accessible as Yahoo. myproject. mymodule. mypublicproperty .";
  4. Mypublicmethod: function (){
  5. Yahoo. Log ("I'm accessible as Yahoo. myproject. mymodule. mypublicmethod .");
  6. }
  7. };
  8. } (); // Here, brackets are used to execute the anonymous function and return

Note that the bottom line ending with curly braces is followed by a pair of parentheses (). This symbol means to immediately execute the anonymous function and return an object containing mypublicproperty and mypublicmethod. As long as the anonymous function can return, the returned object can be accessed using Yahoo. myproject. mymodule.
3. Add "private" methods and variables (before return) to anonymous functions first ).
So far, all we have done is to directly allocate mypubilcproperty and mypublicmethod to Yahoo. myproject. mymodule. In addition, this mode allows us to execute some code before return:

 


 

Private variables such as myprivateproperty and myprivatemethod can only be accessed by anonymous functions or members of returned objects. Although anonymous functions are executed and terminated immediately, they are retained. With the power of closure, as long as Yahoo. myproject. mymodule needs them, so our two variables will not be destroyed.

4. Practice this modeLet's take a look at the practical application of module pattern. If you have a list, some items in the list can be dragged. The dragged item has a draggable CSS class.

  1. <! -- This script file except des all of the Yui utilities: -->
  2. <SCRIPT type = "text/JavaScript" src = "http://yui.yahooapis.com/2.2.2/build/utilities/utilities.js"> </SCRIPT>
  3. <Ul id = "mylist">
  4. <Li class = "draggable"> item one. </LI>
  5. <Li> item two. </LI> <! -- Item two won't be draggable -->
  6. <Li class = "draggable"> item three. </LI>
  7. </Ul>
  8. <SCRIPT>
  9. Yahoo. namespace ("myproject ");
  10. Yahoo. myproject. mymodule = function (){
  11. // Reference the abbreviation of Yui utilities:
  12. VaR Yue = Yahoo. util. event,
  13. Yud = Yahoo. util. Dom;
  14. // Private Method
  15. VaR getlistitems = function (){
  16. // Note that we use other private variables, including the abbreviation of "Yud"
  17. VaR ellist = Yud. Get ("mylist ");
  18. VaR alistitems = Yud. getelementsbyclassname (
  19. "Draggable", // get the item with only the "draggable" CSS class
  20. "Li", // only returns the list item
  21. Ellist // restrict the children of the element to be searched
  22. );
  23. Return alistitems;
  24. };
  25. // The returned object becomes Yahoo. myproject. mymodule:
  26. Return {
  27. Adragobjects: [], // save dd objects for external access
  28. Init: function (){
  29. // Wait until the Dom is fully loaded before creating the list item:
  30. Yue. ondomready (this. makelisdraggable, this, true );
  31. },
  32. Makelisdraggable: function (){
  33. VaR alistitems = getlistitems (); // these elements can be dragged.
  34. For (VAR I = 0, j = alistitems. length; I <j; I ++ ){
  35. This. adragobjects. Push (new Yahoo. util. dd (alistitems [I]);
  36. }
  37. }
  38. };
  39. } (); // Here, brackets are used to execute the anonymous function and return
  40. // The above code is executed, so we can access init
  41. Yahoo. myproject. mymodule. INIT ();
  42. </SCRIPT>
XML Code
This is a simple example, which is especially complicated. If we do this, we believe that we can write more compact code. However, the scaling mode will increase with the complexity of the project, and the API will become larger and larger. This method avoids the global namespace and supports public access to API methods. It supports protection or "private" data.

 

 

JS Code
  1. Yahoo. myproject. mymodule = function (){
  2. // "Private variable ":
  3. VaR myprivatevar = "I can be accessed only from within Yahoo. myproject. mymodule .";
  4. // "Private method ":
  5. VaR myprivatemethod = function (){
  6. Yahoo. Log ("I can be accessed only from within Yahoo. myproject. mymodule ");
  7. }
  8. Return {
  9. Mypublicproperty: "I'm accessible as Yahoo. myproject. mymodule. mypublicproperty ."
  10. Mypublicmethod: function (){
  11. Yahoo. Log ("I'm accessible as Yahoo. myproject. mymodule. mypublicmethod .");
  12. // Within myproject, I can access "private" vars and methods:
  13. Yahoo. Log (myprivatevar );
  14. Yahoo. Log (myprivatemethod ());
  15. // The native scope of mypublicmethod is myproject; we can
  16. // Access public members using "this ":
  17. Yahoo. Log (this. mypublicproperty );
  18. }
  19. };
  20. } (); // Here, brackets are used to execute the anonymous function and return

In the above Code, an object containing two members is returned from an anonymous function. You can use this. mypublicproperty and this. mypublivmethod to access the Yahoo. myproject. mymodule. Outside yahoo. myproject. mymodule, these announcement members can access Yahoo. myproject. mymodule. mypublicproperty and Yahoo. myproject. mymodule. mypublicmethod.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.