2014-09-05 38 views
0

我已经接管了一个使用JavaScript的现有项目,方法如下。我想了解如何/为什么这样做,并获得更多有关如何有效使用它的信息。这种模式有没有名称,所以我可以做更多的研究?这个JavaScript模式是如何调用的?如何以正确的方式使用它?

的index.html(前</body>

<script src="main.js"></script> 
<script src="navigation.js"></script> 
<script> 
    var navigation = new window.Navigation(); 
    window.App.navigation = navigation; 
    window.App.navigation.init(this); 
</script> 

main.js(简称...)

App = {}; 
$(document).ready(function(){ 
    console.log('doc ready'); 
}); 

navigation.js(简称...)

window.Navigation = (function() { 
return function() { 
    return { 
     scope: undefined, 
     someElement:undefined, 

     init: function (pScope) { 
      this.scope = pScope; 
      this.someElement = $(this.scope.querySelectorAll('.some-element')); 
      this.someMethod(); 
     }, 
     someMethod: function() { 
      // some jQuery 
      if($(this).hasClass('some-class')) { 
       self.anotherMethod(); 
      } 
     }, 
     anotherMethod: function() { 
      // some jQuery 
      $(this.someElement).show(); 
      this.yetAnotherMethod(); 
     }, 
     yetAnotherMethod: function() { 
      // some jQuery 
      $(this.someElement).stop().animate({duration:200}); 
     } 
    }; 
}; 
}()); 

除了了解这个模式是什么以及为什么会使用它,我还有一个实际的问题:

navigation.js控制器负责我们的元素.navigation。现在,如果有多个.navigation,与一个.avigation元素进行交互会导致所有.navigation元素对交互作出反应。

我该如何触发控制器来控制每个.navigation元素本身? (我希望我的词汇量是正确这里)

它的工作原理,如果我在使用jQuery以下方式调用控制器(里面的index.html),但感觉不对:

+0

'someMethod'看起来像是有一个引用'this'的错误,也不推荐使用'window.',而是直接引用变量 – 2014-09-05 20:30:24

+0

你确定这个工作正常吗?在脚本中插入一些警报或控制台日志以查看JS是否被触发。 – 2014-09-05 20:37:11

+0

是的,它的工作原理。我刚刚简化了代码,因为原来的东西需要很长的时间才能在这里发布。 – maze 2014-09-05 20:42:24

回答

1

也就是说一个JavaScript Object Literal或Singleton模式。这里是一个非常简单的例子:

<script> 

var exampleObj = { 

    settings : { 
     'test' : 'example' 
    }, 

    alertSettings : function(){ 
     alert(this.settings.test); 
    }, 

    gotCha : function(){ 
     var self = this; 
     $('body').animate({"background-color":"red"},2000,function(){ 
      alert(self.settings.test); 
      self.alertSettings(); 
     }); 
    }, 

    init : function() { 
     this.alertSettings(); 
     this.gotCha(); 
    } 

} 

exampleObj.init(); // triggers the events 

</script> 

初始化触发alertSettings()方法,然后gotCha()。您会注意到gotCha()重新声明thisself。这是因为gotCha()中的某个函数内有一个函数,而this对它所包含的函数的限制(或范围)。所以内部函数引用self别名(或clojure),因为它想要警告的变量位于外部函数this中。

快速而肮脏。我希望这有帮助。 *需要jQuery

+0

很好的答案。至于其他方面,'$('。navigation')。each(function()'each是不必要的。类命令将自动为所有具有该类的元素启动。如果你只想调用它,给它一个id ,或者使用遍历选择符,比如':nth-​​child(n)'或':first()'等 – briansol 2014-09-05 20:37:14

+0

如果我想将事件附加到单个元素,我会使用.bind()然后引用单击的元素, $('。classString')。bind('click',function(e){$(e.target).css('background-color':'red'); alert('woot');});' – 2014-09-05 20:43:19

+0

假设我有两个元素.navigation ...我希望它们的行为相同。例如,如果我单击.open按钮,我想滑动它。导航打开或其他。但当然,如果我想打开导航我不想同时打开导航B.但这正是现在正在发生的事情 - 除非我使用jQuery方法。 – maze 2014-09-05 20:44:25

相关问题