Pass Initialized Object Reference to Event

V

vunet

If I initializer my object as

var obj = new SomeObject();

then I have some method inside of the object as:

function SomeObject(){
.......
this.showLink = function(){
return "<a href='javascript:void(0)' onClick='obj.showMessage()'></
a>"
}
this.showMessage = function(){ alert("My Message is Here") }
.......
}

Obviously, "onClick='obj.showMessage()' " is a wrong refrence because
we may call it obj2 or have multiple objects. How can I reference any
function of an initialized object on click of a link?
Thank you for suggestions.
 
T

Thomas 'PointedEars' Lahn

vunet said:
If I initializer my object as

var obj = new SomeObject();

then I have some method inside of the object as:

function SomeObject(){
......
this.showLink = function(){
return "<a href='javascript:void(0)' onClick='obj.showMessage()'></
a>"
}
this.showMessage = function(){ alert("My Message is Here") }
......
}

Obviously, "onClick='obj.showMessage()' " is a wrong refrence because
we may call it obj2 or have multiple objects. How can I reference any
function of an initialized object on click of a link?

Don't use strings. And move all methods that don't require a closure to the
prototype object.

function isMethod(o, p)
{
return (o && /\s*(function|object|unknown)\s*/i.test(typeof o[p])
&& o[p]);
}

function SomeObject()
{
this.showLink = function() {
if (isMethod(document, "createElement"))
{
var a = document.createElement("a");

if (a)
{
a.href = "javascript:void(0)";

var me = this;
var f = function(e) {
me.showMessage();

if (isMethod(e, "preventDefault")) e.preventDefault();
if (typeof e.returnValue != "undefined") e.returnValue = false;
return false;
};

if (isMethod(a, "addEventListener"))
{
a.addEventListener("click", f, false);
}
else
{
a.onclick = f;
}
}
}

return a;
};
}

SomeObject.prototype = {
constructor: SomeObject,
showMessage: function(){ alert("My Message is Here") }
};

That said, don't misuse `a' elements like this.
Thank you for suggestions.

You're welcome.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top