If I create a class like this:
function MyClass(input){
// construct something;
var myInstanceName = ???
}
I'll need the name of the instance when creating an instance...
var MyInstance = new MyClass("Make Something");
Need to know myInstanceName (="MyInstance" in this case) because there is a method that creates buttons and the "onclick" must call a method of this instance.
I tried "this.name" but it returns undefined... How do I get this value?
EDIT: Here is a tested working example:
function MyClass(WhereGoesTheButton){
this.myName = "Test"; // <-- here is the issue
this.idButton = WhereGoesTheButton;
//
}
MyClass.prototype.createButton = function(){
document.getElementById(this.idButton).innerHTML = '<button id="myId" onclick="'+this.myName+'.callBack(this);">Press Here</button>';
}
MyClass.prototype.callBack = function(who){
alert("Button "+who.id+" has been pressed!");
}
var Test = new MyClass("testArea");
//
function ini(){
Test.createButton();
}
Just put it in a page with body onload ini() and some div to create the button.
It works, but alternatives with better practices are welcome!
EDIT 2: this will do the job, although we still got no name of the instance:
var MyClassId = 0;
function MyClass(WhereGoesTheButton){
this.myButtonId = "MyClass"+String(MyClassId);
MyClassId++;
this.idButton = WhereGoesTheButton;
//
}
MyClass.prototype.createButton = function(){
var me = this;
document.getElementById(this.idButton).innerHTML = '<button id="'+this.myButtonId+'" >Press Here</button>';
document.getElementById(this.myButtonId).addEventListener("click", function(e){ me.callBack(this); }, false);
}
MyClass.prototype.callBack = function(who){
alert("Button "+who.id+" has been pressed!");
}
var Test = new MyClass("testArea");
//
function ini(){
Test.createButton();
}
Simple code example:
function Parent(){
// custom properties
}
Parent.prototype.getInstanceName = function(){
for (var instance in window){
if (window[instance] === this){
return instance;
}
}
};
var child = new Parent();
console.log(child.getInstanceName()); // outputs: "child"
Need to know myInstanceName (="MyInstance" in this case) because there is a method that creates buttons and the "onclick" must call a method of this instance.
Why do you need the variable name for that? Your method can reference the current instance with this.
However, inside a click handler this will be the clicked element. Assuming you're bind the event somewhat like this:
someElement.addEventListener('click', this.someMethod, false);
... you can change it to:
var that = this;
someElement.addEventListener('click', function(e) {
that.someMethod()
}, false);
There are other possible solutions too, like bind and the EventListener interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With