Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Singleton

I have something like in a file say test.js:

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

Now if test.js is loaded twice in my page i.e. src=test.js in two different locations, it gives alert twice. I want it to be like a singleton. Any ideas on how to achieve this?

like image 865
Alec Smart Avatar asked Feb 14 '11 08:02

Alec Smart


3 Answers

Use a conditional shortcut:

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

jQuery.test();

!$.test evaluates to true if $.test is not defined and the code on the rightside after the && is executed. Otherwise, it'll just skip the part. Another useful pattern for that could look like:

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

This does the same thing actually. If $.test is already defined its used, otherwise assign the anonymous function to $.test. Both versions can (and probably should) get optimized but not just checking if they were defined, but also if they are from type function.

like image 180
jAndy Avatar answered Nov 04 '22 06:11

jAndy


Have you tried something like this?

if(typeof $.test == "undefined") {
  (function($){    
    $.test= function(){ 
      alert('test');
    }
  })(jQuery);
  jQuery.test();
}
like image 44
Benson Avatar answered Nov 04 '22 06:11

Benson


(function($){    
  $.test = function() {
    if (!$.test.hasBeenRun) {
      $.test.hasBeenRun = true;
      alert('test');
    }
  }
  $.test.hasBeenRun = false;
})(jQuery);
jQuery.test();
like image 36
Alex Wayne Avatar answered Nov 04 '22 08:11

Alex Wayne