jQuery Plugin variable availability -
today first time, ran problem variables being mixed multiple instances of jquery plug-ins.
a simple version of plug-in can viewed here: http://jsfiddle.net/jydzb/2/
i want able create timer in plugin, , access variable "mytimer" in method within plugin. in case, destroy it. however, thought sure creating variables did below "mytimer" made variable available in class/plugin? wrong? how use variables within plugin? know store them in $obj.data('',''), doesn't make sense when store in var.
you see when run jsfiddle script, doesn't destroy timer.
simple html
write line every 5 seconds... destroy after 10:<br /> <hr /> <div id='mydiv' style='border: solid 1px #000;float:left;'></div> <div id='mydiv2' style='border: solid 1px #f00;float:right;'></div>
jquery plugin
if (jquery) ( function (jquery) { var mytimer; var methods = { init: function () { return this.each(function () { var $obj = $(this); var data = $obj.data('init'); if (!data) { mytimer = setinterval(function(){ writeline($obj) }, 1000); $obj.data('init', true); $obj.data('cnt',0); } }); }, destroy: function () { var $obj = $(this); $obj.data('init', false); clearinterval(mytimer); $obj.append("destroyed!"); } }; $.fn.timeit = function (method) { if (methods[method]) { return methods[method].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('method ' + method + ' not exist on jquery.timeit'); } }; } )(jquery); $('#mydiv').timeit(); $('#mydiv2').timeit(); function writeline(cobj) { cobj.data('cnt',cobj.data('cnt')+1); cobj.append("another line written...(" + cobj.data('cnt') + ")<br />"); if(cobj.data('cnt')>=10){ cobj.timeit('destroy'); } }
i think usage of variable scoped @ level fine, aside fact you're assigning value of mytimer inside of each
(different context each time). if remove second wire-up ($('#mydiv2').timeit();
) works champ. storing variable instance more appropriate.
Comments
Post a Comment