if ($('invoice_discount')) {
this.invoice_discount = this.form.down('#invoice_discount');
this.invoice_discount.observe('change', this._checkFormat.bindAsEventListener(this));
}
if ($('invoice_vat')) {
this.invoice_vat = this.form.down('#invoice_vat');
this.invoice_vat.observe('change', this._checkFormat.bindAsEventListener(this));
}
if ($('invoice_salestax')) {
this.invoice_salestax = this.form.down('#invoice_salestax');
this.invoice_salestax.observe('change', this._checkFormat.bindAsEventListener(this));
}
if ($('invoice_freight')) {
this.invoice_freight = this.form.down('#invoice_freight');
this.invoice_freight.observe('change', this._checkFormat.bindAsEventListener(this));
}
Refactorings
No refactoring yet !
paul.wilkins.myopenid.com
November 1, 2009, November 01, 2009 19:54, permalink
Edit: using a normal for loop, as with for...in on an array there's no guarantee that other properties aren't prototyped in addition
var fields = ['invoice_discount', 'invoice_vat', 'invoice_salestax', 'invoice_freight'],
i,
field;
for (i = 0; i < fields.length; i++) {
field = fields[i];
this[field] = this.form.down('#' + field);
this[field].observe('change', this._checkFormat.bindAsEventListener(this));
}
James
November 4, 2009, November 04, 2009 21:33, permalink
Agreed with TJ
$A(['discount', 'vat', 'salestax', 'freight']).each(function(id) {
this['invoice_' + id] = this.form.down('#invoice_' + id);
this['invoice_' + id].observe('change', this._checkFormat.bindAsEventListener(this));
}.bind(this));
Thomas Salvador
November 15, 2009, November 15, 2009 11:10, permalink
hi.
i think the versions of paul and james should be combined.
removed the redundant field name calculation to get it down from three concatenations to two, per field. (compiler might optimize this on its own.)
$A(['discount', 'vat', 'salestax', 'freight']).each(function(id) {
fullfield = 'invoice_' + id;
this[fullfield] = this.form.down('#' + fullfield);
this[fullfield].observe('change', this._checkFormat.bindAsEventListener(this));
}.bind(this));
I have the following code that works. However, it is the same pattern over and over. How do I refactor this into a loop?