jQuery callback into non-jQuery parent object
See this code:
var MyObject = new function() {
this.tos = new Array();
this.show = function() {
this.clearTimeouts();
$("#divExample").slideDown(null,function() {
MyObject.tos[MyObject.tos.length] =
setTimeout(function(){MyObject.doSomething();} , 1800);
});
return;
};
this.doSomething = function() {
return;
};
开发者_C百科 this.clearTimeouts = function(){
for (var i=0; i<this.tos.length; i++)
clearTimeout(this.tos[i]);
this.tos = new Array();
return;
};
}
MyObject and it's methods are used in a few places. Maybe it's a bad way to do it, I dunno. I didn't want to tie it too closely with jQuery for my own reasons, so leaving it like this made sense as I can easily change the slide to style.display.
The problem is that I dont like referencing the object as MyObject in the callback of the jQuery slide, but I have to to add the timeout reference to my array of them so they can all be cleared. Is there a better way to do this?
Thanks!
You could try something like this:
this.show = function() {
var obj = this;
obj.clearTimeouts();
$("#divExample").slideDown(null,function() {
obj.tos[obj.tos.length] =
setTimeout(function(){obj.doSomething();} , 1800);
});
return;
};
var MyObject = (function() {
// private variable
tos = new Array();
// private method
function doSomething() {
// do something
// ..
}
// return an instance with public methods
return {
show: function() {
this.clearTimeouts();
$("#divExample").slideDown(null,function() {
tos[tos.length] =
setTimeout(function(){ doSomething(); } , 1800);
});
},
clearTimeouts: function() {
for (var i=0; i<tos.length; i++)
clearTimeout(tos[i]);
tos = new Array();
}
}
};
精彩评论