How to call a function in jquery plugin?

(function($) { $.fn.top_islides = function(){ var ajax_init = function(){ init_islides(); setTimeout(function(){picmove()},300); }; //..... }; })(jQuery); 

call it in doucument ready in another file

 $('#top_slides').top_islides(); $('#top_slides').top_islides().ajax_init(); 

I thought this would work, I have an error, what is the problem?

+7
source share
4 answers

Do it like this:

 (function($) { //Assuming $.fn.top_islides is defined $.fn.top_islides.ajax_init = function(){ init_islides(); setTimeout(picmove,300); }; //..... })(jQuery); 

or

 (function($) { $.fn.top_islides = function(){ var ajax_init = function(){ init_islides(); setTimeout(picmove,300); }; return { ajax_init: ajax_init }; }); //..... })(jQuery); 
+5
source

Try something like this, as in the example below: -

 <script type="text/javascript"> $.someplugin = { CallMe : function() { alert("You called?"); }, otherstuff : function() { alert("other stuff!"); } }; $.someplugin.CallMe(); $.someplugin.otherstuff(); </script> 
+3
source

when using var inside a function, it will make the element "private". this is a hacker way to make Javascript work, while the true structure of the class does not get into Javascript. You need to either install it on the prototype of your function, or return an object

 (function($) { $.fn.top_islides = function(){ var ajax_init = function(){ init_islides(); setTimeout(function(){picmove()},300); }; return { 'ajax_init': ajax_init }; //..... }; })(jQuery); 

or

 (function($) { $.fn.top_islides = function(){ //..... }; $.fn.top_islides.prototype.ajax_init = function(){ init_islides(); setTimeout(function(){picmove()},300); } })(jQuery); 

but in your case, you will not use the prototype, because you are not creating an instance of the new top_islides object, but rather accessing through jQuery, so the first option is your best bet.

0
source

Imo, the best solution is a trigger that is cleaner because you can save the plugin plugin system.

You can declare an event handler in your plugin declaration and fire it from the outside:

 (function($) { $.fn.top_islides = function(){ this.on ('init_islides', function(){ setTimeout(function(){picmove()},300); }; //..... }; })(jQuery); $( "button" ).click(function () { $( "p" ).trigger( "init_islides"); }); 

DOC can be found here: http://api.jquery.com/on/

0
source

All Articles