I created some JavaScript classes and FunctionFactories for them, but I believe there are errors in my implementation.
To make the code more understandable, I decided to rename certain parts of it.
The main class is called the "root"-class, which has children that are added later on.
function templateRoot(){
this.id = "root";
this.parent = null;
this.children = [];
this.editable = true; // bla
this.render = function(){
$.each(this.children,function(i,obj){
this.children[i].render();
var baseButtons = this.getBaseButtons();
$('#'+this.id).append(baseButtons);
});
};
this.addBase = addBaseFactory(this);
};
The "addBase" attribute receives a function from the addBaseFactory...
function addBaseFactory(that){
return function(){
var newBase = new base(that.children.length, that.id);
that.children.push(newBase);
};
}
...and here is the base class used to generate an object in the "addBase" method:
function base(count, parent){
this.id = parent+"_base"+count;
this.parent = parent;
this.children = [];
this.remove = function (){
$('#'+this.id).remove();
};
this.render = baseRenderFactory(this);
this.addChild = addChildFactory(this);
this.getBaseButtons = function(){
var addAttributeButton = new $("<button>+ Attribute</button>").button();
var addTextButton = new $("<button>+ Text</button>").button();
return [addAttributeButton, addTextButton];
};
}
The issue arises when debugging the code and setting a breakpoint within the "render" function of the root-object. At this point, "this" refers to the "base" object instead of the "root" object. This confuses me because the "root" object should be the owner of this function, and the base has its own render function which is not directly called there.
Even in the line:
$.each(this.children,function(i,obj){
"this" points to the "base" object while it should be referring to the "root" object.
I hope someone can assist me with this :-)
EDIT:
The code to execute it:
var test = new templateRoot();
test.addBase();
test.render();
EDIT 2:
In the "addBaseFactory," "that" correctly references the "base" object.