Using Event Handler to call obj method from within a method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jezternz
    New Member
    • Jan 2008
    • 145

    Using Event Handler to call obj method from within a method

    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.method 1 and theclass.method 2.

    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.
    Code:
    theobj = new theclass();
    theobj.method1();
    
    function theclass(){
     // whatever goes here
    }
    
    theclass.prototype.method1(){
     window.addEventListener
      ?window.addEventListener('resize',[B]this.method2[/B],false)
       :attachEvent('onresize',[B]this.method2[/B]);
    }
    
    theclass.prototype.method2(){
     // do lots of stuff
    }
    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
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    as I understand it right, "this" conforms to the calling object (in this case window (note: window.attachEv ent()) you should rather refer to theclass.method 2.

    regards

    Comment

    • rnd me
      Recognized Expert Contributor
      • Jun 2007
      • 427

      #3
      you don't need to pass it, you can close it:

      Code:
      theclass.prototype.method1(){
        [B]var that =this; [/B]
      window.addEventListener
        ?window.addEventListener('resize',[B]that[/B].method2,false)
         :attachEvent('onresize',[B]that[/B].method2);
      }

      Comment

      • Jezternz
        New Member
        • Jan 2008
        • 145

        #4
        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?

        Comment

        • gits
          Recognized Expert Moderator Expert
          • May 2007
          • 5390

          #5
          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:

          [code=javascript]
          function theclass(){
          this.foo = 'my_foo';
          }

          theclass.protot ype.method1 = function() {
          var that = this;
          var handler = function(e) {
          that.method2.ap ply(that, arguments);
          };

          if(window.addEv entListener) {
          window.addEvent Listener('click ', handler, false);
          } else {
          window.attachEv ent('onclick', handler);
          }
          }

          theclass.protot ype.method2 = function() {
          alert(this.foo) ;
          }

          var theobj = new theclass;
          theobj.method1( );
          [/code]
          kind regards

          Comment

          • Jezternz
            New Member
            • Jan 2008
            • 145

            #6
            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

            Code:
            	this.SizeWDS();	 // Note this method works fine when called by itself
            	
                var that = this;
                var handler = function(e) {
                    alert('moving'); // works fine
                    that.SizeWDS.apply(that, arguments); // has no effect?
                    alert('moving'); // weid thing is this also works fine
                };
            	
            	window.addEventListener?
            	 window.addEventListener('resize',handler,false)
            	  :attachEvent('onresize',handler);
            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

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5390

              #7
              Originally posted by Jezternz
              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, ...
              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 :)

              Originally posted by Jezternz
              ... secondly, why are these "function(e )" found around what does adding the "e" there do?
              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:

              [code=javascript]
              theclass.protot ype.method2 = function(e) {
              alert(this.foo) ;
              }[/code]

              Comment

              • rnd me
                Recognized Expert Contributor
                • Jun 2007
                • 427

                #8
                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:

                Code:
                function greaterThan(num){ return num > this; }
                [,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:

                Code:
                function greaterThan(num){ return num > this; }
                  alert(  greaterThan.call(2,7)  )//true
                  alert(  greaterThan.call(12,7)  )//false
                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.

                Comment

                • Jezternz
                  New Member
                  • Jan 2008
                  • 145

                  #9
                  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.

                  Comment

                  Working...