I'm trying to refactor a chunk of code that acts on each variable found in the variables array through by means of putting the variable name and its corresponding callback into an object that is easily iterated through. The problem is that variables[0].callback ends up undefined when calling Foo.bar(data). The functionality of the entire object needs to remain in the object itself.
So far my only solution has been to define the functions when they are assigned to the callback variables but this is less than ideal because the callbacks themselves cannot access the required variables.
...
{name: "x", callback: function() {...}},
...
Desired Functionality:
console.log(Foo.variables[0].callback != undefined) //true
Foo.bar(); //Will print "y"
Am I missing something silly? Or should I be using another pattern to tackle this particular problem?
Thanks for the help!
var Foo = {
variables: [
{name: "x", callback: this.funX},
{name: "y", callback: this.funY},
{name: "z", callback: this.funZ}
],
//For this example, data could be the following object
// data = {x: 0, y: 1, z: 0};
bar: function(data) {
this.variables.forEach(function(elem) {
if(data[elem.name] == 1)
elem.callback();
});
},
funX: function() {
console.log(this.variables[0].name);
},
funY: function() {
console.log(this.variables[1].name);
},
funZ: function() {
console.log(this.variables[2].name);
}
}
Somewhat relevant:
javascript: call function inside object, from a callback function
thisworks in JavaScript. MDN this - JavaScriptthisclearly does not work in thevariablesarray which is what I'm trying to fix but otherwise, I'm not sure you are correct.