Reputation: 992
Today for the first time, I ran into a problem where variables were being mixed up with multiple instances of jQuery plug-ins.
A simple version of my plug-in can be viewed here: http://jsfiddle.net/jydzB/2/
I want to be able to simply create a timer in a plugin, and access the variable "myTimer" in another method within the plugin. In this case, to destroy it. However, I thought for sure that creating variables like I did below with "myTimer" made that variable available only in that class/plugin? Am I wrong? How do I use variables within a plugin? I know I could store them in $obj.data('',''), but that doesn't make sense to do that when you could simply store it in a var.
You will see that when you run the jsFiddle script, it doesn't destroy the timer.
Simple HTML
Write a line every five seconds... destroy it 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 + ' does 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');
}
}
Upvotes: 1
Views: 213
Reputation: 16944
I think usage of a variable scoped at that level is fine, aside from the fact that you're assigning the value of myTimer inside of your each
(different context each time). If you remove the second wire-up ($('#myDiv2').timeIt();
) it works like a champ. Storing the variable with the instance would probably be more appropriate.
Upvotes: 1