JS設計模式(三)

單例,使用命名空間結合單例實現

 

  1. /* Using a namespace. */
  2. var MyNamespace = {
  3. findProduct: function(id) {
  4. ...
  5. },
  6. // Other methods can go here as well.
  7. }

使用單例的一個例子

 

  1. /* RegPage singleton, page handler object. */
  2. GiantCorp.RegPage = {
  3. // Constants.
  4.     FORM_ID: 'reg-form',
  5.     OUTPUT_ID: 'reg-results',
  6.     // Form handling methods.
  7.     handleSubmit: function(e) {
  8.         e.preventDefault(); // Stop the normal form submission. 阻止普通表單提交
  9.         var data = {};
  10.         var inputs = GiantCorp.RegPage.formEl.getElementsByTagName('input');
  11.         // Collect the values of the input fields in the form.
  12.         for(var i = 0, len = inputs.length; i < len; i++) {
  13.             data[inputs[i].name] = inputs[i].value;
  14.         }
  15.         // Send the form values back to the server.
  16.         GiantCorp.RegPage.sendRegistration(data);
  17.     },
  18.     sendRegistration: function(data) {
  19.         // Make an XHR request and call displayResult() when the response is
  20.         // received.
  21.         ...
  22.     },
  23.     displayResult: function(response) {
  24.         // Output the response directly into the output element. We are
  25.         // assuming the server will send back formatted HTML.
  26.     GiantCorp.RegPage.outputEl.innerHTML = response;
  27.     },
  28. // Initialization method.
  29.     init: function() {
  30.     // Get the form and output elements.
  31.     GiantCorp.RegPage.formEl = $(GiantCorp.RegPage.FORM_ID);
  32.     GiantCorp.RegPage.outputEl = $(GiantCorp.RegPage.OUTPUT_ID);
  33.     // Hijack the form submission.
  34.     addEvent(GiantCorp.RegPage.formEl, 'submit', GiantCorp.RegPage.handleSubmit);
  35.     }
  36. };
  37. // Invoke the initialization method after the page loads.
  38. addLoadEvent(GiantCorp.RegPage.init);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章