I'm building a javascript library with a friend that's supposed to make HTML5 game creation easier (but it's really just for fun) and here's some code I'm having trouble with:
/* Calls f on all the elems of the list that pass p and implement f */
var apply = function (f, p, list) {
for (var i in list) {
if (p(list[i]) === true && list[i][f] != undefined && typeof list[i][f] === 'function') {
list[i][f]();
}
}
};
this.draw = function(p) {
apply(moveView, p, this.views);
};
The user would call the this.draw function and pass it a predicate. The function moveView that's being passed into the apply function would only be executed if every object in the views array implemented it.
However, my console is throwing an error saying "moveView is not defined" which makes sense because . At the point that I call my apply function, I don't want the interpreter to check if moveView exists or not, I just want to pass it in so I can check if each object that's being applied to, implements that function. I thought that maybe calling apply like apply("draw", p, this.views);
would work but that didn't either because then in the apply function, f is not a function anymore, it's a string. I really just want to be able to pass any generic function name to my apply function so that I can then do all the checking inside there.
All my code can be found on my Github.
EDIT:
/*View object*/
var View = (function(){
var constr = function(f, o, i){
this.frame = utility.checkFrame(f);
this.orient = utility.checkOrientation(o);
/*user identification string*/
this.id = i;
this.moveView = function(){
console.log("testing");
};
};
return constr;
}());
I figured it out. It was in my View object:
var View = (function(){
this.moveView = function(){
console.log("testing");
};
var constr = function(f, o, i){
this.frame = utility.checkFrame(f);
this.orient = utility.checkOrientation(o);
/*user identification string*/
this.id = i;
};
return constr;
}());
I moved moveView outside the View object constructor and an error was no longer thrown. It was an issue of scope.