473,667 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Attach a class method to event handler

Ugo
Hi guys,

until now I make so:

[html]
<div id="my_div"><!-- content --></div>

[simple-js]
MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
var selfObj = this;
document.getEle mentById('my_di v').onclick = function ( e )
{
selfObj.doSomet hingWith( e || event );
}
}

How do I avoid the closure of my object reference?
And MyClass is not a Singleton...
Jun 27 '08 #1
10 1789
On May 29, 8:36 am, Ugo <priv...@nospam .itwrote:
Hi guys,

until now I make so:

[html]
<div id="my_div"><!-- content --></div>

[simple-js]
MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
var selfObj = this;
document.getEle mentById('my_di v').onclick = function ( e )
{
selfObj.doSomet hingWith( e || event );
}

}

How do I avoid the closure of my object reference?
And MyClass is not a Singleton...
if you want to avoid the closure then don't create one with selfObj.

MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}

}

or perhaps even

MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick =
MyClass.prototy pe.doSomethingW ith;
}
It may be a mistake to be thinking in terms of "MyClass" as JavaScript
doesn't have classes.

Peter
Jun 27 '08 #2
Peter Michaux wrote:
On May 29, 8:36 am, Ugo <priv...@nospam .itwrote:
>until now I make so:

[html]
<div id="my_div"><!-- content --></div>

[simple-js]
MyClass.protot ype.doSomething = function( ) {};
MyClass.protot ype.assignFun = function( )
{
var selfObj = this;
document.getEle mentById('my_di v').onclick = function ( e )
{
selfObj.doSomet hingWith( e || event );
}
}

How do I avoid the closure of my object reference?
MyClass.prototy pe.assignFun = function() {
document.getEle mentById('my_di v').onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
};

That said, you should avoid mixing "DOM Level 0" and DOM Level 2 features in
one statement; at least you should feature-test both before you mix them.
Such Reference Worms[tm] are error-prone anyway. Consider this (still
error-prone because of the partially proprietary, apparently untestable
approach):

MyClass.prototy pe.assignFun = function() {
if (isMethod(docum ent, "getElementById "))
{
var target = document.getEle mentById('my_di v');
if (target)
{
target.onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
}
}
};
>And MyClass is not a Singleton...

if you want to avoid the closure then don't create one with selfObj.

MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}
}
While this is not the least equivalent to the original, `MyClass' is the
bound "variable" of the closure then.
or perhaps even

MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick =
MyClass.prototy pe.doSomethingW ith;
}
It is getting worse. Now the method of the prototype object will be called
as a method of the Global Object.
It may be a mistake to be thinking in terms of "MyClass" as JavaScript
doesn't have classes.
That, at least, is correct.
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Jun 27 '08 #3
On May 30, 10:35 am, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
[...]
That said, you should avoid mixing "DOM Level 0" and DOM Level 2 features in
one statement; at least you should feature-test both before you mix them.
Such Reference Worms[tm] are error-prone anyway. Consider this (still
error-prone because of the partially proprietary, apparently untestable
approach):

MyClass.prototy pe.assignFun = function() {
if (isMethod(docum ent, "getElementById "))
{
var target = document.getEle mentById('my_di v');
if (target)
{
target.onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
}
Doesn't that create a circular reference to the DOM element referenced
by target? Should that be avoided by using, at this point:

target = null;

}
};

--
Rob
Jun 27 '08 #4
On May 29, 5:35 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Peter Michaux wrote:
On May 29, 8:36 am, Ugo <priv...@nospam .itwrote:
until now I make so:
[html]
<div id="my_div"><!-- content --></div>
[simple-js]
MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
var selfObj = this;
document.getEle mentById('my_di v').onclick = function ( e )
{
selfObj.doSomet hingWith( e || event );
}
}
How do I avoid the closure of my object reference?

MyClass.prototy pe.assignFun = function() {
document.getEle mentById('my_di v').onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
};

That said, you should avoid mixing "DOM Level 0" and DOM Level 2 features in
one statement; at least you should feature-test both before you mix them.
Such Reference Worms[tm] are error-prone anyway. Consider this (still
error-prone because of the partially proprietary, apparently untestable
approach):

MyClass.prototy pe.assignFun = function() {
if (isMethod(docum ent, "getElementById "))
{
var target = document.getEle mentById('my_di v');
if (target)
{
target.onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
}
}
};
And MyClass is not a Singleton...
if you want to avoid the closure then don't create one with selfObj.
MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}
}

While this is not the least equivalent to the original, `MyClass' is the
bound "variable" of the closure then.
or perhaps even
MyClass.prototy pe.doSomething = function( ) {};
MyClass.prototy pe.assignFun = function( )
{
document.getEle mentById('my_di v').onclick =
MyClass.prototy pe.doSomethingW ith;
}

It is getting worse. Now the method of the prototype object will be called
as a method of the Global Object.
It wasn't clear what the code in the original post was doing or even
if the doSomething function uses "this". Without a complete question a
complete answer is not possible.

[snip]

Peter
Jun 27 '08 #5
Peter Michaux wrote:
On May 29, 5:35 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
>Peter Michaux wrote:
>>[...]
MyClass.proto type.doSomethin g = function( ) {};
MyClass.proto type.assignFun = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}
}

While this is not the least equivalent to the original, `MyClass' is the
bound "variable" of the closure then.
>>or perhaps even

MyClass.proto type.doSomethin g = function( ) {};
MyClass.proto type.assignFun = function( )
{
document.getEle mentById('my_di v').onclick =
MyClass.prototy pe.doSomethingW ith;
}
It is getting worse. Now the method of the prototype object will be called
as a method of the Global Object.

It wasn't clear what the code in the original post was doing or even
if the doSomething function uses "this". Without a complete question a
complete answer is not possible.
You are winding around the issue.

It does not matter whether the purpose of the code was clear (to you) or
not; using the `this' reference in a prototype method and using the
reference to the prototype object there are clearly not the same thing, nor
are assigning the reference to a prototype method versus assigning a
reference to a Function object that calls this prototype method (as
inherited through the prototype chain). So it cannot be expected to have
the same outcome, and is therefore not the least equivalent to one another.

Host objects aside, consider this (in Fx 2.0.0.14):

function MyObject(answer ) {
this.bar = function() {
window.alert(an swer);
};
}

MyObject.protot ype.foo = function() {
// 42
this.bar();

// 23,function MyObject...
MyObject.protot ype.bar();

var f = MyObject.protot ype.bar;

// 23,[Window]
f();
};

MyObject.protot ype.bar = function() {
window.alert([23, this.constructo r]);
}

(new MyObject(42)).f oo();

Trimming quotes a bit more would increase the chance of your postings being
recognized in the future.
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Jun 27 '08 #6
Thomas 'PointedEars' Lahn a écrit :
Trimming quotes a bit more would increase the chance of your postings being
recognized in the future.
FFS, who do you think you are ? Go to hell !

--
laurent
Jun 27 '08 #7
Ugo
>>[simple-js]
>>MyClass.proto type.doSomethin g = function( ) {};
MyClass.proto type.assignFun = function( )
{
var selfObj = this;
document.getEle mentById('my_di v').onclick = function ( e )
{
selfObj.doSomet hingWith( e || event );
}
}

How do I avoid the closure of my object reference?

MyClass.prototy pe.assignFun = function() {
document.getEle mentById('my_di v').onclick = (function(o) {
return function(e) {
o.doSomethingWi th(e || window.event);
};
})(this);
};

That said, you should avoid mixing "DOM Level 0" and DOM Level 2 features in
one statement;
i.e.?
Where did I mix?
So, if I am not mistaken, you make a closure too:
your approach is more elegant, but you close the parameter "o" of the
anonymous function, or not?
at least you should feature-test both before you mix them.
it was only example...
Jun 27 '08 #8
On May 30, 4:43 am, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Peter Michaux wrote:
On May 29, 5:35 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Peter Michaux wrote:
[...]
MyClass.protot ype.doSomething = function( ) {};
MyClass.protot ype.assignFun = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}
}
While this is not the least equivalent to the original, `MyClass' is the
bound "variable" of the closure then.
>or perhaps even
>MyClass.protot ype.doSomething = function( ) {};
MyClass.protot ype.assignFun = function( )
{
document.getEle mentById('my_di v').onclick =
MyClass.prototy pe.doSomethingW ith;
}
It is getting worse. Now the method of the prototype object will be called
as a method of the Global Object.
It wasn't clear what the code in the original post was doing or even
if the doSomething function uses "this". Without a complete question a
complete answer is not possible.

You are winding around the issue.
No I'm not.
It does not matter whether the purpose of the code was clear (to you) or
not;
If the question is not clear then many answers are possible.
using the `this' reference in a prototype method
There was no use of "this" in the original question.
and using the
reference to the prototype object there are clearly not the same thing, nor
are assigning the reference to a prototype method versus assigning a
reference to a Function object that calls this prototype method (as
inherited through the prototype chain). So it cannot be expected to have
the same outcome, and is therefore not the least equivalent to one another.
But it may have acceptable outcome. The question was not clear. That
was actually one point I was making with my original answer.

[snip]
Peter
Jun 27 '08 #9
Peter Michaux wrote:
On May 30, 4:43 am, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
>Peter Michaux wrote:
>>On May 29, 5:35 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Peter Michaux wrote:
[...]
MyClass.pro totype.doSometh ing = function( ) {};
MyClass.pro totype.assignFu n = function( )
{
document.getEle mentById('my_di v').onclick = function ( e )
{
MyClass.prototy pe.doSomethingW ith( e || event );
}
}

While this is not the least equivalent to the original, `MyClass' is the
bound "variable" of the closure then.
[...]
It wasn't clear what the code in the original post was doing or even
if the doSomething function uses "this". Without a complete question a
complete answer is not possible.
You are winding around the issue.

No I'm not.
You are overlooking something important, then.
>It does not matter whether the purpose of the code was clear (to you) or
not;

If the question is not clear then many answers are possible.
True. However, a good answer would at least provide an equivalent solution
to the presented problem (which was, without doubt, how to avoid closures).
Yours did not provide an equivalent solution. (Mine did provide a
equivalent solution, but maybe no solution to the OP's problem. Insofar
both of us might have failed to provide a good answer.)
>using the `this' reference in a prototype method

There was no use of "this" in the original question.
My example shows that this does not matter. Literally.

I have trimmed the quote more so that you may see the point more easily.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3484
by: SunshineGirl | last post by:
In my code, class A instanciates classes B and C. I would like class B to connect an event handler to a method in class A, and for class C to disconnect that event handler. I think I've done too much thinking, and now I'm even more confused as to how to accomplish this as when I started. Any help will be appreciated.
5
3153
by: Andy | last post by:
Hi all, I have a site with the following architecture: Common.Web.dll - Contains a CommonPageBase class which inherits System.Web.UI.Page myadd.dll - Contains PageBase which inherits CommonPageBase - Contains myPage which inherits PageBase Each of these classes overrides OnInit and ties an event handler
4
1416
by: Hardy Wang | last post by:
Hi, I have two classes (ClassA and ClassB), public ClassA { public ClassA() { this.MyButton.Clicked += new System.EventHandler(this.MyButton_Click); } private void MyButton_Click(object sender, System.EventArgs e) {
13
2440
by: pamelafluente | last post by:
Hello. I have written the following code (this code is on a control): Sub InitSomething() mSet(me.FindForm) End Sub Sub mSet(ByVal f As Control) For Each t As Control In f.Controls If TypeOf t Is ToolStripMenuItem Then AddHandler t.MouseEnter, AddressOf Me.SetSemaforoMenu
1
3226
by: Bob | last post by:
Hi, I am having trouble seeing how this bolts together. The UI starts a process which involves a long running database update. All Database activity is handled by a class called DT. DT has a progress event. So I added a bw to the form. The Dowork Calls a method which instantiates a DT and calls its Dataprocessing method.
3
1813
by: polocar | last post by:
Hi, I'm writing a C# program (using Visual Studio 2005 Professional Edition). I have defined a class MyPanel in the following way: class MyPanel : Panel { ... }
21
2369
by: John Henry | last post by:
Hi list, I have a need to create class methods on the fly. For example, if I do: class Dummy: def __init__(self): exec '''def method_dynamic(self):\n\treturn self.method_static("it's me")''' return
1
1685
by: =?Utf-8?B?RGF2ZQ==?= | last post by:
I have a class that Form1 calls to do some work. I would like to report back progress from the class to a richtextbox, will call it m_report, on the form. Like in the class, Form1.m_report.Text= "Calculating variable 10"; How would I do that.
1
3357
by: AliR \(VC++ MVP\) | last post by:
Hi Everyone, I have a few form classes that inherit from the same base class. The main reason that this is done is that some event handlers are common between these classes and I was trying to save time and not have to put a event handler in every form class. The base class has an event handler for Edit.Enter and Edit.Leave so that it can turn the Edit menu items on and off.
0
8459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8367
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8889
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8570
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8650
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7391
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.