473,414 Members | 1,775 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,414 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 6004
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....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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,...
0
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...
0
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...
0
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...
0
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,...

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.