473,385 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Object oriented javascript & events

I'm trying to do the following:

function row() {
this.selected = false;
this._el = document.createElement("TR");
this._el.attachEvent("onClick", this.rowClick);
}

row.prototype.rowClick = function() {
this.selected = true;
}

var r = new row();

The rowClick event doesn't work however, because "this" doesn't point
to the row object in the rowClick function. How do I get "this" to
point to the row object?

Jul 23 '05 #1
6 1669
What i do to solve this is to have your object have a unique ID. Attach
this id to any HTML elements that are part of the object. Now store the
object in a global array, indexed at it's unique ID. When the attached
function is fired, you inspect the event.srcElement element and extract
the id.

ex: event.srcElement.getAttribute('uid');

Now use the uid to get the object from the global array, voila

Jul 23 '05 #2
b.***@gmx.net writes:
function row() {
this.selected = false;
this._el = document.createElement("TR");
this._el.attachEvent("onClick", this.rowClick);


The attachEvent method is a proprietary IE method. Amongst its other
problems, it doesn't call the function as a property of the object
it is attached to (so "this" is not set).

In comparison, the W3C version,
this.addEventListener("click", this.rowClick, true)
does.

Notice that it doens't matter that you write "this.rowClick". It simply
evaluates to the function, with no reference to the "this" object. It
is the event handling that must set the object of the call.

A solution for attachEven:

var self = this;
this.attachEvent("onclick", function(){self.rowClick();})

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3

I've also struggled with this for a bit and think I've found the best
solution to achieve OO 'this' keyword re-entry from an event handler.
I've only tested this in Safari and so have not tested the
'attachEvent' part (IE) lately but the func.apply(object) but works
fine using addEventListener.

Philip Weaver
function EventManager() {

this.registerClickEvent = EventManager_RegisterClickEvent;
}

function EventManager_RegisterClickEvent(element, object, func) {

var f = function() {
func.apply(object);
};

if (element.attachEvent) {
element.attachEvent("onclick", f);
} else {
element.addEventListener("click", f, false);
}
}
--
philmaker
------------------------------------------------------------------------
philmaker's Profile: http://www.highdots.com/forums/member.php?userid=219
View this thread: http://www.highdots.com/forums/showthread.php?t=1303766

Jul 23 '05 #4

Also added event passing...

function EventManager() {

this.registerClickEvent = EventManager_RegisterClickEvent;
}

function EventManager_RegisterClickEvent(element, object, func) {

var f = function(e) {
if (e == null) {
e = window.event;
}
func.call(object, e);
};

if (element.attachEvent) {
element.attachEvent("onclick", f);
} else {
element.addEventListener("click", f, false);
}
}
--
philmaker
------------------------------------------------------------------------
philmaker's Profile: http://www.highdots.com/forums/member.php?userid=219
View this thread: http://www.highdots.com/forums/showthread.php?t=1303766

Jul 23 '05 #5

I could be mistaken, but looks you're reinventing the wheel? Setting a
listener for an event with a native listener method?

Danny
On Thu, 09 Jun 2005 14:54:54 -0700, philmaker
<ph**************@no-mx.forums.yourdomain.com.au> wrote:

Also added event passing...

function EventManager() {

this.registerClickEvent = EventManager_RegisterClickEvent;
}

function EventManager_RegisterClickEvent(element, object, func) {

var f = function(e) {
if (e == null) {
e = window.event;
}
func.call(object, e);
};

if (element.attachEvent) {
element.attachEvent("onclick", f);
} else {
element.addEventListener("click", f, false);
}
}


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #6
On 09/06/2005 22:21, philmaker wrote:
I've also struggled with this for a bit and think I've found the best
solution to achieve OO 'this' keyword re-entry from an event handler.
There are numerous ways, and the best depends solely on current
requirements.

[snip]
function EventManager() {

this.registerClickEvent = EventManager_RegisterClickEvent;
}
If registerClickEvent is the only property, then EventManager would be
better as an object:

var EventManager = {
registerClickEvent : function(...) {
...
}
};
function EventManager_RegisterClickEvent(element, object, func) {

var f = function() {
func.apply(object);
};
Or:

function f() {
func.call(object);
}
if (element.attachEvent) {
element.attachEvent("onclick", f);
} else {
element.addEventListener("click", f, false);
}
}


This isn't good in general for a couple of reasons:

1. As the inner function, f, will survive after registerClickEvent is
called, it will form a closure that keeps all of the arguments to
the outer function in memory. In IE, this will cause a memory leak
because element is a DOM object and not subject to JScript's
garbage collection mechanism.
2. Both the Function.prototype.apply and .call methods are late
additions to JScript. Versions prior to 5.5 (therefore usually
IE 5.5, too) do not implement them, so the inner function will
cause a run-time error when called.
3. If a browser doesn't support the attachEvent method, it doesn't
automatically mean it supports the addEventListener method. Indeed,
some user agents will support neither, but can have function
references assigned to event properties. As the attachEvent
mechanism doesn't set the this operator correctly, it is usually
better to avoid using it.

Many of the regulars, myself included, have posted code that will add
multiple listeners to an element, and avoid issues (1) and (3).
Emulation to avoid issue (2) is just as abundant.

As most listeners aren't useful as public methods, a variation of
Lasse's suggestion will usually do:

function MyObject() {
var self = this;

function listener() {
/* Use self to refer to the object instance and
* the this operator to refer to the element.
*/
}

this.attach = function(element) {
/* Using the addEventListener method for simplicity. */

element.addEventListener('click', listener, false);
};
}

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #7

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

Similar topics

11
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in...
6
by: Alejandro Penate-Diaz | last post by:
Hi. I was handling key events nicely using some Javascript on my apps using something like this: this.txtUserName.Attributes.Add("onkeydown","if((event.which && event.which == 13)||(event.keyCode...
4
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in...
4
by: Greg | last post by:
I'm guessing the problem I'm having has something to do with Master Pages or DetailsView because the exact same code works fine on a page without a Master Page and DetailsView controls. The...
11
by: Nathan Sokalski | last post by:
I add several JavaScript events (onchange, onkeypress, etc.) to Controls using the Add method of the Attributes collection. However, if the JavaScript code contains certain characters, such as & or...
28
by: ensemble | last post by:
I'm trying to utilized a more object-oriented approach to managing window events in javascript. Thus, I am creating a "controller" object to handle events and interact with the server. However, I...
5
by: KimmoA | last post by:
Does C have a future? I'd like to think so, but nobody seems to agree with me. Of course, I don't use C in my profession, and maybe I wouldn't be using it if I had the pressure to actually produce...
0
by: dolittle | last post by:
Hi, I'm embedding a last.fm flash widget. I want to be able to remove it from the page using javascript. I've tried to delete the html element that contains the code but it keeps playing in...
3
by: notnorwegian | last post by:
i have some confusion over this. sure a class is basically a classification, like for example an animal or flower. and an object/instance of that class is then for example a cat. an object is...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...

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.