472,958 Members | 2,162 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

adding event inside a object constructor

8
Hi.

I want to add an event handler inside a function that will be used has an object constructor. The event handler to be added is an "method" of the object.

if i do this:

Expand|Select|Wrap|Line Numbers
  1. function Someobj(element) {
  2.  this.num = 1;
  3.  this.inc = function() {
  4.   ++this.num;
  5.  }
  6.  this.element = element;
  7.  element.addEventListener('click', function(event) { this.inc(); }, false);
  8. }
  9. var so1 = new Someobj(document.getElementById('Photo1'));
  10. var so2 = new Someobj(document.getElementById('Photo2'));
  11.  
This gives an exception. The problem is then the event listener is called the "this" reference is no longer the object but it is the html element that generated the event.

if i declare a local var to store the this reference so the function in the event handler can find the correct object, something like this:
Expand|Select|Wrap|Line Numbers
  1. function Someobj(element) {
  2.  var me = this;
  3.  this.num = 1;
  4.  this.inc = function() {
  5.   ++this.num;
  6.  }
  7.  this.element = element;
  8.  element.addEventListener('click', function(event) { me.inc(); }, false);
  9. }
  10. var so1 = new Someobj(document.getElementById('Photo1'));
  11. var so2 = new Someobj(document.getElementById('Photo2'));
  12.  
this will not work either because the "me" reference is always set to the last object that was created an not the object that registered the event.

How do i solve this?
Any ideas???
Oct 9 '08 #1
4 5852
rnd me
427 Expert 256MB
a little bit of this and that goes a long way.
Expand|Select|Wrap|Line Numbers
  1.  
  2. function Someobj(element) {
  3.  var that = this;
  4.  this.num = 1;
  5.  this.inc = function() {
  6.   ++this.num;
  7.  }
  8.  this.element = element;
  9.  element.addEventListener('click', function(event) { that.inc(); }, false);
  10. }
that will bring closure to the matter.
Oct 9 '08 #2
xend
8
a little bit of this and that goes a long way.
Expand|Select|Wrap|Line Numbers
  1.  
  2. function Someobj(element) {
  3.  var that = this;
  4.  this.num = 1;
  5.  this.inc = function() {
  6.   ++this.num;
  7.  }
  8.  this.element = element;
  9.  element.addEventListener('click', function(event) { that.inc(); }, false);
  10. }
that will bring closure to the matter.
I thought that if it was that way the variable "that" would behave like a static variable for the constructor function. But i tested it and it works.

Thank you.
Oct 9 '08 #3
rnd me
427 Expert 256MB
yes, it does work.

that's the magic of closure: variables inside of functions are preserved, even after that function returns. sub-functions defined inside the constructor have full access to variables defined in the constructor.
Oct 9 '08 #4
gits
5,390 Expert Mod 4TB
yes that's a really nice and useful feature of javascript ... just a short snippet that shows how you may use it:

Expand|Select|Wrap|Line Numbers
  1. function OBJ(param) {
  2.     // a private variable = only
  3.     // accessible in the constructor
  4.     var foo = 'bar';
  5.  
  6.     // a public variable accessible 
  7.     // from everywhere as an instance-
  8.     // variable 
  9.     this.foobar = 'barfoo';
  10.  
  11.     // a privileged method that returns
  12.     // you the value of the private var
  13.     // foo
  14.     this.get_foo = function() {
  15.         return foo;
  16.     };
  17.  
  18.     // a privileged method that returns
  19.     // you the value of param that was
  20.     // passed to the constructor
  21.     this.get_param = function() {
  22.         return param;
  23.     };
  24. }
  25.  
  26. var o = new OBJ('my_foo');
  27.  
  28. // alerting the value of the instance-var
  29. alert(o.foobar);
  30.  
  31. // trying to alert the val of the private var foo
  32. alert(o.foo);
  33.  
  34. // using the privileged getters
  35. alert(o.get_foo());
  36. alert(o.get_param());
  37.  
kind regards
Oct 10 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

28
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()',...
10
by: tony kulik | last post by:
This code works fine in ie and opera but not at all in Mozilla. Anybody got a clue as to how to get it right? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <script...
34
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and...
9
by: JamesB | last post by:
I want progress on my ftp upload, so I am trying to add an event. All the FTP stuff is in its own class (FTPClient). In the class header I have: Public Event SendProgress(ByVal bytes As Integer)...
0
by: Patrick Lioi | last post by:
We have form that is used as the base class of all of our forms, let's call it BaseApplicationForm. We have another form, say ChildApplicationForm that inherits from BaseApplicationForm. The...
15
by: glenn | last post by:
Hi folks, I have a DropDownList in a DataGrid that is populated from records in a database. I want to add a value that might be a string such as "Select a Company" for the first item since an...
6
by: Kevin Attard | last post by:
I am using a GridView inside a UserControl which has a template column for deleting the rows. Before databinding the gridview i am attaching the RowCommand and RowDataBound event. I am using the...
0
by: sukeshchand | last post by:
How to create an event object in a dll without adding the dll into the project ie.; i use CreateObject() to create an instance of an object in a dll without adding the dll into the project. it is ok...
3
by: =?Utf-8?B?d2Vic211cmY=?= | last post by:
dear newsgroup member, I want to access a label in a form (form1.cs) from a class file (periodicUpload.cs). The label in form1.cs is a status Indicator. PeriodicUpload.cs is a timer class file....
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.