Monday, October 27, 2008

Dynamic Size Arrays in javascript

Recently I needed to create a dynamic array in javascript. I didn't want to have two complete arrays defined and choose based off an if statement. So to do this I used the push() command. It easily allowed me to tailor the contents of the array based on various boolean flags. The array I was creating was for the tools param of a new Ext.Panel object. As you can see in the sample code below, the publish button is only added to the tool array if the isShareable flag is true.

var tools = [];

tools.push({
id:'toggle',
handler: this.onToggle.createDelegate(this),
qtip: "toggle"
});
tools.push({
id:'help',
handler: this.onHelp.createDelegate(this),
qtip: "help"
});
tools.push({
id:'gear',
handler: this.onConfigure.createDelegate(this),
qtip: "configure"
});
tools.push({
id:'refresh',
handler: this.onRefresh.createDelegate(this),
qtip: "refresh"
});
if (this.isShareable) {
tools.push({
id:'save',
handler: this.onPublish.createDelegate(this),
qtip: "publish"
});
}
tools.push({
id:'close',
handler: this.onClose.createDelegate(this),
qtip: "close"
});