javascript - How to get variable into chained function with mootools -
i've created function spice html forms check if fields valid on submit, , if not flashed red warn users. works great until tries return color normal.
if (response.length > 0) { (var = 0; < response.length; i++) { if (response[i].getattribute('field') != '') { var errfield = $(response[i].getattribute('field')+'err'); if (errfield) { errfield.set('html', response[i].getattribute('msg')); var color = errfield.getstyle('color'); window['cfx'+i] = new fx.morph(errfield, { duration: 400, transition: fx.transitions.quad.easeinout }); window['cfx'+i].start({'color': '#000000'}).chain(function() { window['cfx'+i].start({'color': color}); }); } } } }
i've debugged point can tell crashed when gets inside chained function, because loses variable @ point. i've looked around , can't figure out how i
chain function work.
erm. basically, iterator run , value of i
passed chained function index of last item in iteration, always.
several things can - local closure near calls 1 or rewriting whole loop use array.prototype.each
so:
response.each(function(el, i){ if (el.getattribute('field') != ''){ var errfield = $(el.getattribute('field') + 'err'); if (errfield){ errfield.set('html', el.getattribute('msg')); var color = errfield.getstyle('color'); window['cfx' + i] = new fx.morph(errfield, { duration: 400, transition: fx.transitions.quad.easeinout }); window['cfx' + i].start({'color': '#000000'}).chain(function(){ window['cfx' + i].start({'color': color}); }); } } });
the value of i
above fixed iterator within function scope each iteration, hence producing desired effect.
alternatively these work:
// permanent reference var cfx = window['cfx' + i]; cfx.start({'color': '#000000'}).chain(function(){ cfx.start({'color': color}); }); // binding function via outer scope element window['cfx' + i].start({'color': '#000000'}).chain(function(){ this.start({'color': color}); }.bind(window['cfx' + i])); // encapsulating local closure (function(i){ // immutable here window['cfx' + i].start({'color': '#000000'}).chain(function(){ window['cfx' + i].start({'color': color}); }); }(i));
and finally, scope of chained functions fx instance, keeps reference element being chained in this.element
point element , this
instance, hence can do:
window['cfx' + i].start({'color': '#000000'}).chain(function(){ this.start({'color': color}); });
that's it. have fun
Comments
Post a Comment