473,387 Members | 1,585 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,387 software developers and data experts.

Using Event Handler to call obj method from within a method

Jezternz
145 100+
Ok, I am new to JS OOP, so bare with me.

The code is quite large so I will summaries and simplify, to show the piece that isn't working.
Ok I have defined a class and then an object with several methods.I call these:
theclass, theclass.method1 and theclass.method2.

Now what I want to do is from inside method1, I want to register an event handler for say "window" to run method2 on the current object.

Heres some code, and if I haven't explained something clearly, please ask questions.
Expand|Select|Wrap|Line Numbers
  1. theobj = new theclass();
  2. theobj.method1();
  3.  
  4. function theclass(){
  5.  // whatever goes here
  6. }
  7.  
  8. theclass.prototype.method1(){
  9.  window.addEventListener
  10.   ?window.addEventListener('resize',this.method2,false)
  11.    :attachEvent('onresize',this.method2);
  12. }
  13.  
  14. theclass.prototype.method2(){
  15.  // do lots of stuff
  16. }
  17.  
  18.  
Problem is it is not using "this" as the current object, so the browser thinks the method is invalid. I have tried putting this into a variable and passing that, this also does not work.

Please don't say the event listener wont work with ie6/other browsers, thats not important as this stage.

Thanks heaps in advance, Josh
Dec 5 '08 #1
8 3708
Dormilich
8,658 Expert Mod 8TB
as I understand it right, "this" conforms to the calling object (in this case window (note: window.attachEvent()) you should rather refer to theclass.method2.

regards
Dec 5 '08 #2
rnd me
427 Expert 256MB
you don't need to pass it, you can close it:

Expand|Select|Wrap|Line Numbers
  1. theclass.prototype.method1(){
  2.   var that =this; 
  3. window.addEventListener
  4.   ?window.addEventListener('resize',that.method2,false)
  5.    :attachEvent('onresize',that.method2);
  6. }
Dec 5 '08 #3
Jezternz
145 100+
yeah, I tried that rnd_me, didn't work, just tried again, in case I missed something, still no luck. Maybe theres a way to get around this. (by the way when I do what you say, debug says, the method doesn't exist for the object). Dormilich I like that idea, however I want to associate the event with the particular object not the class and i think your correct on what this refers to in this particular case.

Thanks for the idea's so far, Should I maybe post full code?
Dec 5 '08 #4
gits
5,390 Expert Mod 4TB
hi ...

your example just gave me a syntax error in firebug ... i just changed it a bit and it works that way - method2 is now called in the theclass's execution-context:

Expand|Select|Wrap|Line Numbers
  1. function theclass(){
  2.     this.foo = 'my_foo';
  3. }
  4.  
  5. theclass.prototype.method1 = function() {
  6.     var that = this;
  7.     var handler = function(e) {
  8.         that.method2.apply(that, arguments);
  9.     };
  10.  
  11.     if(window.addEventListener) {
  12.         window.addEventListener('click', handler, false);
  13.     } else {
  14.         window.attachEvent('onclick', handler);
  15.     }
  16. }
  17.  
  18. theclass.prototype.method2 = function() {
  19.     alert(this.foo);
  20. }
  21.  
  22. var theobj = new theclass;
  23. theobj.method1();
  24.  
kind regards
Dec 5 '08 #5
Jezternz
145 100+
This seems like progress, however it still isnt working correctly, im not sure if its something I did or what.
Heres the actual practical part im working with

Expand|Select|Wrap|Line Numbers
  1.     this.SizeWDS();     // Note this method works fine when called by itself
  2.  
  3.     var that = this;
  4.     var handler = function(e) {
  5.         alert('moving'); // works fine
  6.         that.SizeWDS.apply(that, arguments); // has no effect?
  7.         alert('moving'); // weid thing is this also works fine
  8.     };
  9.  
  10.     window.addEventListener?
  11.      window.addEventListener('resize',handler,false)
  12.       :attachEvent('onresize',handler);
  13.  
Thanks for your input gits, if its not too much trouble, would you be able (or anyone else) to explain a couple of things. First of all, what is the apply methods practical use / how is it used and secondly, why are these "function(e)" found around what does adding the "e" there do?

Thanks, Josh

Edit:
I found gits code does work, thanks heaps, was a problem with my method ><, sorry bout that, still would apreciate any help with my couple of questions (above).


Thanks guys, much apreciated
Dec 5 '08 #6
gits
5,390 Expert Mod 4TB
@Jezternz
the apply() method binds a method to the passed execution context ... in our case we bind it to the 'theclass' object through closuring the this with that :)

@Jezternz
e is just the event that is passed to the event-handler ... typically you want to process it in the handler-code itself, so you might wnat to use: e.type or e.target or whatever.

and of course the method2 in my above example has to receive the arg or args like this:

Expand|Select|Wrap|Line Numbers
  1. theclass.prototype.method2 = function(e) {
  2.     alert(this.foo);
  3. }
Dec 5 '08 #7
rnd me
427 Expert 256MB
to expand:

"this" has several meaning in javascript depending upon context. there's at least 4 main usages, and if we get picky there could be about 10 distinct roles that "this" can play.

"this" - where you use it: what it means (4 big ones)
  • outside of any function: window
  • inside an object method, or prototype method: parent object
  • in an event: the tag or object raising or defining the event
  • in a constructor: the object being created
the main thing to know about call() and apply() is that they can change the meaning of the word "this" inside a function.
doing so allows the function to use a different "this" than a new blank object.
it lets you use the function code slightly like a template, substituting different things at later times.


it pops up here to avoid the problem of ambiguity; events on html have a "this" that means the tag where the event is bound, while your object's "this" meant your object. by using apply, we can specify exactly which one we are wanting to use.

it can also be used intrinsically though functional programming jobs like array.filter.
consider:

Expand|Select|Wrap|Line Numbers
  1. function greaterThan(num){ return num > this; }
  2. [,1,2,3,4,5].filter(greaterThan, 2)//[3,4,5]
we can see that "this" is simply a placeholder in this syntax, and 2 becomes our "this".

we can use the same function without an array by using apply or call:

Expand|Select|Wrap|Line Numbers
  1. function greaterThan(num){ return num > this; }
  2.   alert(  greaterThan.call(2,7)  )//true
  3.   alert(  greaterThan.call(12,7)  )//false
  4.  
usage:
call: function.call( thisMeans, argument1);

call is the same as apply with one minor difference: apply takes an array as the second argument whereas call takes the arguments like regular function parameters, one argument to call for each argument in the function.
the first argument of both determines what will be used for "this" when executing the function.
Dec 5 '08 #8
Jezternz
145 100+
I think I understand what apply/call does now, and the function(e). I will play around with a bit and try get used to using them.

Thanks again, gits and rnd_me, you were both very helpful.
Dec 5 '08 #9

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

Similar topics

3
by: Peter Schmitz | last post by:
Hi, how can raise an event that is handled by an event handler? I simply want to execute the code that is attached to a 'click'- event of a button from anywhere in my code. How can I do this? ...
8
by: Mark | last post by:
Hi, I'm looking for some ideas on how to build a very simple Event processing framework in my C++ app. Here is a quick background ... I'm building a multithreaded app in C++ (on Linux) that...
4
by: Pai | last post by:
hello there, I am trying to rersize the window it works find in IE but doea not work with mozilla window.attachEvent(onload,MWSOnLoad); window.onload = function (MWSOnLoad) { alert('hello');...
4
by: Wee Bubba | last post by:
the following event handler checks to see if any parent control has attached to the event 'SearchItemSelect'. i use it for event bubbling whenever one of my search items has been selected and at...
4
by: Anders | last post by:
Hi, I was wondering what is most efficient of the two. Is it more efficient to add server controls within the Itemtemplate and use OnItemDataBound to manipulate and databind the servercontrols. ...
5
by: Stan Sainte-Rose | last post by:
Hi, Which event is called when the user click on the close window icon (X) ? I want, when he clicks on this icon, to display a message before closing the form. If he replys by No, I don't want to...
2
by: Phill. W | last post by:
How do I propagate an Event that I've just handled? I have a UserControl containing, among other things, a TextBox. The UserControl handles KeyDown/KeyPress Events for both itself and the...
7
by: Peter Row | last post by:
Hi, I've started work on my own control some parts of which use standard controls, others I need to draw on my controls surface to get the display output I require, however.... I seem to be...
8
by: Roger | last post by:
When I call the session.abandon() method, it calls the session_end event. When a user closes the browser or clicks the log off button, I can dispose of objects and abandon the session cleaning....
6
by: Murray Hopkins | last post by:
Hi. THE QUESTION: How do I get a reference to my Object when processing an event handler bound to an html element ? CONTEXT: Sorry if it is a bit long. I am developing a JS calendar tool....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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:
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: 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
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
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,...
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...

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.