I have a small problem using private variables in a JavaScript function. This software depends on draw2d, a rendering library for javascript. The library forces you to use John Resig's implementation of Class.js, which allows for simple Java like class inheritance, and what i believe is the root of the problem.
//= require block/XBlock.js
console.log("sblock loaded.");
xmicro.block.SimpleBlock = xmicro.block.XBlock.extend({
NAME: "xmicro.block.SimpleBlock",
init: function(path, width, height,input,output,contextMenua){
this._super(path,width,height,input,output,contextMenua);
image = path;
this.contextMenu = contextMenua;
xmicro.istn.BlockAttributeStore[this.id] = new xmicro.block.BlockAttributeStore();
},
getImage: function () {
return this.image;
},
onContextMenu: function (x, y) {
supaId = this.id;
that = this;
var buildFunc = function(){
var args = Array.prototype.slice.call(arguments);
args.push(supaId);
return that.contextMenu.build.apply(null, args);
};
if(this.contextMenu !== undefined){
$.contextMenu({
trigger: "right",
selector: this.contextMenu.selector,
build: buildFunc
});
}
},
getPersistentAttributes: function () {
var memento = this._super();
return memento;
}
});
The comment at the top does some auto concatenation, but the focus of the problem is at the onContextMenu
function. I have a closure there that needs to be called in order to build a jQuery context menu from a properties object. One thing inside that properties object is a method called build
, for which I use buildFunc
to intercept the call and append the id of the figure it was called on.
The problem is that if I declare var supaId = this.id
, as I make more figures of this type, they start sharing supaId, and start cross-contaminating variables. The other problem is that if I use just supaId = this.id
like I below, then it works, but puts supaId on the global scope. Neither of these are good options for me, and I would like to understand how to fix it.
Any help is appreciated!