/    Sign up×
Community /Pin to ProfileBookmark

How can object method be called as element event handler?

I am showing an example of an object constructor below. Suppose one of its methods (“method1”) creates a SPAN node inserted into the HMTL document. The span node will be clicked by the mouse, so an event listener is added. The handler too is a method of the constructed object.

[CODE]function objConstructor(arg) {

this.method1 = function () = {
node = document.createElement(“span”);
node.addEventListener(“click”, function() { this.showElem(true); }, false);
// more code to put text in span, then append note to parent in HTML
};

this.showElem = function(showState) {
if (showState == true)
// code to show the element
else
// code to hide the element
};
}
[/CODE]

The problem is in the 2nd argument of the addEventListener() method, since the scope of the handler call is outside the constructor and a function-not-defined error will be reported.

I am thinking some kind of closure should be defined such that the handler is made a method of the object. The code is proving a challenge however.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meDec 15.2009 — [CODE]function objConstructor(arg) {
[COLOR="Red"] var that=this;[/COLOR]
this.method1 = function () = {
node = document.createElement("span");
node.addEventListener("click", function() { [COLOR="Red"]that[/COLOR].showElem(true); }, false);

...[/CODE]
Copy linkTweet thisAlerts:
@mavigozlerauthorDec 16.2009 — Yep, it worked. TY

(This should have been obvious even to a beginner, right?)
Copy linkTweet thisAlerts:
@rnd_meDec 16.2009 — Yep, it worked. TY

(This should have been obvious even to a beginner, right?)[/QUOTE]


it's not; i see this asked all the time, so don't feel bad...
×

Success!

Help @mavigozler spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...