我接管了一个以下列方式使用JavaScript的现有项目。 我想了解如何/为什么这样做,并获得有关如何有效使用它的更多信息。 这个模式有名称,所以我可以做更多的研究吗?
index.html(在之前)
var navigation = new window.Navigation(); window.App.navigation = navigation; window.App.navigation.init(this);
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,则与一个.navigation元素交互会导致所有.navigation元素对交互作出反应。
如何触发控制器来控制每个.navigation元素? (我希望我的词汇在这里是正确的)
如果我用jQuery以下面的方式调用控制器(在index.html内),它会工作,但感觉不对:
$('.navigation').each(function() { var navigation = new window.Navigation(); window.App.navigation = navigation; window.App.navigation.init(this); });
这是一个JavaScript Object Literal或Singleton模式。 这是一个非常基本的例子:
Init触发alertSettings()
方法然后gotCha()
。 您会注意到gotCha()
this
重新声明为self
。 那是因为在gotCha()
内的函数中有一个函数,并且this
被限制(或作用域)到它所包含的函数中。 因此内部函数引用self
别名(或clojure),因为它想要警告的变量在外部函数中。
又脏又脏。 我希望这有帮助。 *需要jQuery
以上就是jQuery教程分享如何调用此JavaScript模式以及如何以正确的方式使用它?相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/jquerytutorial/541239.html