2011-02-14 114 views
6

我有类似的文件说test.js:jQuery的辛格尔顿

(function($){  
$.test= function(){ 
    alert('test'); 
    } 
})(jQuery); 
jQuery.test(); 

现在,如果test.js在我的网页即SRC在两个不同的位置= test.js加载两次,它给了两次警报。我希望它像一个单身人士。任何想法如何实现这一目标?

+0

如果您尝试避免两次_calling_测试或_defining_测试两次,有点不清楚。 – 2011-02-14 08:21:39

回答

7

使用条件的快捷方式。和&&后的rightside的代码被执行,否则,它会直接跳过的一部分,另一个有用的模式可能看起来像:。

$.test = $.test || function() { 
    alert('test'); 
} 

这确实的实际上同样的事情如果$.test已被定义其使用,否则将匿名功能分配给$.test。两种版本都可以(也可能应该)进行优化,但不仅仅是检查它们是否已定义,还包括是否来自function

0

你试过类似的东西吗?

if(typeof $.test == "undefined") { 
    (function($){  
    $.test= function(){ 
     alert('test'); 
    } 
    })(jQuery); 
    jQuery.test(); 
} 
0
(function($){  
    $.test = function() { 
    if (!$.test.hasBeenRun) { 
     $.test.hasBeenRun = true; 
     alert('test'); 
    } 
    } 
    $.test.hasBeenRun = false; 
})(jQuery); 
jQuery.test(); 
0

你为什么不提取此共享代码到第三个文件?

除此之外,它取决于代码的作用。如果没有定义$.test

(function($){  
    !$.test && $.test= function(){ 
     alert('test'); 
    } 
})(jQuery); 

jQuery.test(); 

!$.test计算为true:一般来说,你可以换全功能的条件下,只有实行“如果有冲突的事情尚未进行