Attaching an Event Handler(my own Object Method) ??

Discussion in 'Javascript' started by nukiboy@naver.com, May 31, 2005.

  1. Guest

    ========= test.js ===================

    function Test()
    {
    this.temp = "hehehehe" ;

    this.method1 = method1 ;



    }
    function method1()
    {
    alert(this.temp) ;

    }

    ========= test.html =====================

    <BODY>

    <a id="test">aaaaaaaa</a>
    <script>

    var obj = new Test(window) ;

    document.all['test'].attachEvent("onclick",obj.testMethod) ;

    </script>
    </BODY>

    Result :

    This Alert "undefined" !!!

    What?

    Can't I attach my Own Object Method to Target ?

    Please post the answer!!
     
    , May 31, 2005
    #1
    1. Advertising

  2. Random Guest

    wrote:
    > ========= test.js ===================
    >
    > function Test()
    > {
    > this.temp = "hehehehe" ;
    >
    > this.method1 = method1 ;
    >
    >
    >
    > }
    > function method1()
    > {
    > alert(this.temp) ;
    >
    > }
    >
    > ========= test.html =====================
    >
    > <BODY>
    >
    > <a id="test">aaaaaaaa</a>
    > <script>
    >
    > var obj = new Test(window) ;
    >
    > document.all['test'].attachEvent("onclick",obj.testMethod) ;
    >
    > </script>
    > </BODY>
    >
    > Result :
    >
    > This Alert "undefined" !!!
    >
    > What?
    >
    > Can't I attach my Own Object Method to Target ?
    >
    > Please post the answer!!


    Short answer:
    Saying:
    a = b;
    c = b;

    is the same as saying:
    c = a;

    Except for the wasted effort.

    If I say:
    x = new Object();
    x.method = someFunc;

    Then I say:
    document.getElemetById( 'test' ).attachEvent(
    'onclick', x.method );

    It is roughly the same as saying:
    document.getElementById( 'test' ).attachEvent(
    'onclick', someFunc );



    The rest of this post is superfluous, just in case you need a long
    explanation of the above:

    You declare a function:
    function method1( ) {

    You tell it to popup a message displaying the value of a variable. In
    particular, the value of the .temp member of whatever object may
    constitute 'this'.

    You then create an object.
    var obj = new Test( window );

    First: the reference to 'window' here is superfluous. If you're not
    using it, get rid of it.

    More importantly, what this does is instantiate a new Object object and
    calls the constructor function Test().

    Test does this:
    It assigns a String value to the 'temp' member of the new Object
    object.
    It assigns a reference to the method1 function to the 'method1' member
    of the new Object object.


    So if you call it in this way:
    obj.method1()
    Then 'this' refers to 'obj'.


    Your code above says:
    document.all['test'].attachEvent("onclick",obj.testMethod) ;

    I assume you meant:
    document.all['test'].attachEvent("onclick",obj.method1);

    Because you never defined any 'testMethod' anywhere in the entire
    document.

    What this revised version does is assigns a reference to the the
    method1 function to be the onclick event handler of the 'test' element.
    This is the same as assigning it as a method of the HTMLElement object
    in question.

    Same thing as you did when you assigned it to the new Test object,
    isn't it?

    So when onclick gets called, what will happen?
    It is called as:
    document.all['test'].onclick();

    So 'this' will refer to the HTML element called 'test'.


    Probably not a very good explanation. I'm tired. You'll get better
    answers within the next few hours I'm sure.
     
    Random, May 31, 2005
    #2
    1. Advertising

  3. VK Guest

    I guess on the university language it's called "switching the execution
    context"(?) On my language it's called "when THIS becomes THAT" (means
    it points to something you did not expect at all). :)

    In your situation THIS points to the surrent window, and it indeed
    doesn't have any "hehehe" in it.
    You have to use either the abbreviated form: obj.field (naturlich that
    the "obj" has to be global) or the full statement: this.obj.field

    Also please note that your code in miserably IE-dependent and it will
    fail on any more-or-less complicated situation (when your element
    contains any nested elements in it).
    Try my algorythm from
    <http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/5f7aaccb9f46722f/a5395b4a5dd6472b#a5395b4a5dd6472b>

    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    <script>
    function Test() {
    this.field = 'hehehe';
    this.clickMethod =
    function() {
    alert(obj.field);
    }
    }
    </script>
    </head>

    <body bgcolor="#FFFFFF">
    <div id="div1">DIV 1</div>
    <script>
    var obj = new Test();
    document.getElementById('div1').attachEvent('onclick',obj.clickMethod);
    </script>
    </body>
    </html>
     
    VK, May 31, 2005
    #3
  4. nybble Guest

    As random points out - you are trying to call a function directly,
    instead of calling a method on an object. I'm guessing that this is
    just a simplified example for an object with more complexity -
    otherwise it's probably easier to just forget the object and make a
    function directly.

    But, if you need to use an object, here's three ways (of probably many)
    to do it. Depending on your needs. Div1 attaches a function that
    creates an object and then calls the method on each click, Div2
    attaches a function that uses a top level object to call the method on,
    and Div3 attaches a closure with an object built in. I suspect Div2 is
    probably what you are after - if you need an object once, you probably
    want to be able to use it elsewhere, too.

    Anyhow, this code works in firefox you'll need to reconvert it back to
    ie. :)

    <script>
    function Test(msg) {
    this.field = msg;
    }
    Test.prototype.method = function () { alert(this.field) };

    function makeClosure (msg) {
    var testobj = new Test(msg);
    return function () { testobj.method() }
    }

    var div3func = makeClosure('this is div 3');
    var testobj = new Test( 'this is div 2');
    </script>

    <div id="div1">DIV 1</div>
    <div id="div2">DIV 2</div>
    <div id="div3">DIV 3</div>
    <script>
    document.getElementById('div1').addEventListener('click',function () {
    var x = new Test('this is div1'); x.method() },true);
    document.getElementById('div2').addEventListener('click',function () {
    testobj.method() },true);
    document.getElementById('div3').addEventListener('click',div3func,
    true);
    </script>
     
    nybble, May 31, 2005
    #4
  5. On 31/05/2005 15:47, nybble wrote:

    [snip]

    > [...] addEventListener('click', [...] ,true);


    Why are you processing events in the capturing phase?

    [snip]

    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, May 31, 2005
    #5
  6. VK wrote:

    > I guess on the university language it's called "switching the execution
    > context"(?)


    It's called "Quote (the heck) the minimum of what you are referring to!"
    and "different variable object" in this newsgroup and among educated
    ECMAScript/JS programmers.

    > On my language it's called "when THIS becomes THAT" [...]


    How descriptive.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jun 6, 2005
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Cowboy \(Gregory A. Beamer\)

    Attaching to event in container object

    Cowboy \(Gregory A. Beamer\), Oct 24, 2003, in forum: ASP .Net
    Replies:
    2
    Views:
    374
    Cowboy \(Gregory A. Beamer\)
    Oct 28, 2003
  2. Replies:
    1
    Views:
    727
    Damien
    Feb 22, 2007
  3. Joakim Braun
    Replies:
    7
    Views:
    142
    Michael Winter
    Dec 26, 2004
  4. trib
    Replies:
    0
    Views:
    115
  5. Replies:
    0
    Views:
    152
Loading...

Share This Page