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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值