Whats the best way to access testval and testoption inside the foreach loop? This is a mootools draft.
var some = new Class({
options: { testarray: [1,2,3], testoption: 6 },
initialize: function(options) {
this.testval = '123';
this.options.testarray.each(function(el) {
console.log(this.testval);
console.log(this.options.testoption);
});
}
});
UPDATE: I can fix it by adding bind(this) on the array, but is that the way to go?
In cases where I need to reference a number of instance variables from a function that makes this refer to something else I often use var self = this; just before. I find it reads a lot better than binding things all over the place; the self becomes explicitly clear to refer to the instance.
yes, the mootools way to do this is to bind your functions either with
this.options.testarray.each(function(el) {
console.log(this.testval);
console.log(this.options.testoption);
}.bind(this));
or by using the Binds mutator (available in Mootools More, thanks @Dimitar Christoff)
var some = new Class({
options: { testarray: [1,2,3], testoption: 6 },
Implements: Optons,
Binds: ['logOption'],
initialize: function(options) {
this.testval = '123';
this.setOptions(options);
this.options.testarray.each(this.logOptions);
},
logOptions : function(value, index, array) {
// I don't really see the point, but here you are, this code will be executed
// three times, with (1, 0, [1,2,3]), (2, 1, [1,2,3]) and (3, 2, [1,2,3])
console.log(value, index, array);
console.log(this.testval);
console.log(this.options.testoption);
}
});
I moved your each (and not forEach, as said in the comments) inside the initialize(), since I'm not sure code inside the class descriptor object mill work... Also you might want to use the passed options in initialize with this.setOptions(options) and implementing the Options mutator.
Also, as noted in every comment you have var self = this; which is very convenient AND readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With