Dynamically adding and serialising library items in HTML5 canvas and CreateJS
I'd like to serialise (automate) creation of user interface by constructing series of buttons and placing them on a HTML5 canvas. I have JSON file that I read in and construct an array of properties menuItems[], as such:
menuitem[0].title = "Option 1"
menuitem[0].path = "Path 1"
menuitem[1].title = "Option 2"
menuitem[1].path = "Path 2"
menuitem[2].title = "Option 3"
menuitem[2].path = "Path 3"
...
So far, the code I have working looks something like this: _Btn01, _Btn02, _Btn03 are instances of BtnMain button objects added on timeline from library (i.e., not added dynamically)
function BuildUI()
{
root._Btn00._Label.text = menuItems[0].title;
root._Btn01._Label.text = menuItems[1].title;
root._Btn02._Label.text = menuItems[2].title;
...
root._Btn00.id = 0;
root._Btn01.id = 1;
root._Btn02.id = 2;
...
root._Btn00.addEventListener("click", fl_OptHandler.bind(this));
root._Btn01.addEventListener("click", fl_OptHandler.bind(this));
root._Btn02.addEventListener("click", fl_OptHandler.bind(this));
...
}
function fl_OptHandler(e) {
HandleProductOpen(menuItems[e.target.id].path);
}
As I mentioned, the above setup works nicely. However, as it stands, I have to manually count the number of UI items in JSON file and add that many object instances onto the timeline, and assign properties to them one by one. So, I'd like to (obviously) automate this even further, by implementing dynamic object creation based on the length of the JSON UI definition file, something like this:
var _Btns = [];
function createMenu() {
for(var i=0; i<menuItems.length; i++)
{
var button = new lib.BtnMain();
button.id = i;
button.addEventListener("click", fl_OptHandler.bind(root));
_Btns.push(button);
root.addChild(_Btns);
}
}
function fl_OptHandler(e) {
HandleProductOpen(menuItems[e.target.id].path);
}
The createMenu() function goes through and creates the buttons, but the button.id parameter seems not to be assigned properly, and as a result, I am getting an unreferenced object error in fl_OptHandler function. Any idea what am I doing wrong? More generally, how do you serialise and instantiate dynamic object creation? I was hoping that _Btn[0] would be the same (equivalent) as _Btn00 in the first part of the code (that is working), but that doesn't seem to be the case. Any insight is appreciated!
