Call function from within jQuery plugin -
i'm modifying lovely jquery.carousel.js plugin have autochange feature. want use setinterval()
call function, can't play nice.
here code have @ moment:
autoswitch: function() { if(runauto) { $('.next').click(); } }, init: function(el, options) { if(this.options.auto) { setinterval("this.('autoswitch')", this.options.autotime); } }
this snippet , there other stuff, i've left important bits in. line i'm having trouble setinterval("this.('autoswitch')", this.options.autotime);
. whatever try in first argument of setinterval
, doesn't work. so. can awesome people me out how call autoswitch()
setinterval()
function please?
i think you're looking jquery.proxy
:
init: function(el, options) { if(this.options.auto) { // give `setinterval` function call setinterval(jquery.proxy(this.autoswitch, this)), this.options.autotime); } }
jquery.proxy
ensures function gets called correct context (this
value). more general concept here: you must remember this
that's jquery-specific. if want more general solution, can use closure:
init: function(el, options) { var context = this; // remember `this` in variable if(this.options.auto) { // give `setinterval` function call setinterval(function() { // function closure has access // `context`, , can call context.autoswitch(); }, this.options.autotime); } }
that uses closure bind context (see: closures not complicated), usual way this. jquery.proxy
closure behind scenes in well-controlled environment know it's not closing on more data want to.
Comments
Post a Comment