我已经接管了一个使用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),但感觉不对:
'someMethod'看起来像是有一个引用'this'的错误,也不推荐使用'window.',而是直接引用变量 – 2014-09-05 20:30:24
你确定这个工作正常吗?在脚本中插入一些警报或控制台日志以查看JS是否被触发。 – 2014-09-05 20:37:11
是的,它的工作原理。我刚刚简化了代码,因为原来的东西需要很长的时间才能在这里发布。 – maze 2014-09-05 20:42:24