Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    New Coder
    Join Date
    Mar 2009
    Posts
    74
    Thanks
    3
    Thanked 3 Times in 3 Posts

    addEventListener in custom object

    I'm trying to understand how a custom object can call a function within itself. Say I have something like this:

    Code:
    function functiontest()
    {
        
        this.prop1 = '',
        this.prop2 = '',
        this.options = {initiallevels:0},
        this.prop3 = '/blah',
        this.prop4 = true,
    
        this.function4 = function(x)
        {
            console.log(x)
        },
        
        this.init = function(options)
        {
            this.uid=options.uid
            this.t=options.target
            
            document.getElementById(this.t).addEventListener('click',function(){this.uid.function4(this.t)},false)
            
        }
    }
    
    myfun1=new functiontest
    myfun1.init({uid:'myfun1',target:'target1'})
    
    myfun2=new functiontest
    myfun2.init({uid:'myfun2',target:'target2'})
    And the html:

    Code:
    <html>
    <head></head>
    <body>
    
    <div id="target1">T1</div>
    <br>
    <div id="target2">T2</div>
    
    </body>
    </html>

    I don't know what to put in the part in bold to set the click event listener and have it call function4 within the functiontest object. I've tried a bunch of different things and nothing worked. Please help, thanks!
    Last edited by Raphael; 04-05-2012 at 05:57 PM.

  • #2
    New Coder
    Join Date
    Mar 2009
    Posts
    74
    Thanks
    3
    Thanked 3 Times in 3 Posts
    I could do something like:

    document.getElementById(this.t).addEventListener('click',function(evt){var tmp=new functiontest();tmp.function4(this.t)},false)

    and that works, but there's got to be a better way to do it. Any help is appreciated, thanks!

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,080
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by Raphael View Post
    I could do something like:

    document.getElementById(this.t).addEventListener('click',function(evt){var tmp=new functiontest();tmp.function4(this.t)},false)

    and that works, but there's got to be a better way to do it. Any help is appreciated, thanks!
    Sorry, I do not see what is wrong with that code.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #4
    New Coder
    Join Date
    Mar 2009
    Posts
    74
    Thanks
    3
    Thanked 3 Times in 3 Posts
    Quote Originally Posted by Philip M View Post
    Sorry, I do not see what is wrong with that code.
    I guess it's hard to argue for finding a different way to do it if that works. However, is that the best way to do it? It seems like overkill to re-create the entire object everytime just to call 1 function.

    Is there no way to internally reference a function within an object? If not I can just use the temp object as in my example.

    Thank you!

  • #5
    New Coder
    Join Date
    Apr 2011
    Posts
    49
    Thanks
    0
    Thanked 13 Times in 12 Posts
    When an element fires an event, 'this' will point at that element. So you'll have to bind the instance ('this') of functiontest to the eventhandling function belonging to that instance.
    Another problem is that while you can use commas to separate variable, you can't use them to seperate statements. You should use semi-colons for them.
    Code:
    var a = 0,
        b = 1;
    
    this.a = 0;
    this.b = 1;
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    
    <html>
    <head>
    <script>
    function bind(func, object) {
      return function(){
        return func.apply(object, arguments);
      };
    };
    
    function functiontest() {
      this.function = function(x) { alert(x) };
      this.init = function(options) {
        this.t = options.target;
        document.getElementById(this.t).addEventListener('click', bind(function(){this.function(this.t)}, this), false);
      };
    };
    
    window.onload = function() {
      var myfun1 = new functiontest,
          myfun2 = new functiontest;
    
      myfun1.init({uid: 'myfun1', target: 'target1'});
      myfun2.init({uid: 'myfun2', target: 'target2'});
    };
    
    </script>
    </head>
    
    <body>
    <div id="target1">T1</div><br>
    <div id="target2">T2</div><br>
    </body>
    </html>

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Goos View Post
    Another problem is that while you can use commas to separate variable, you can't use them to seperate statements. You should use semi-colons for them.
    That's untrue. You can separate statements using commas - there are even spots in JavaScript where you must use a comma to separate statements because the semi-colon has a different meaning in some parts of JavaScript.

    For example:

    Code:
    for (i= 0, ii = ary.length; i < ii; i++) {...}
    If you used a semi-colon instead of a comma to separate the first two statements there then the outer statement would no longer work.

    It is also common to use commas to separate statements that define variables as there the var at the front of the first statement gets applied to all of the subsequent statements where using a semi-colon instead would change the scope of the other variables being defined. With best practice being to use one var declaration per function using commas for separators allows:

    Code:
    var i= 0, ii = ary.length;
    instead of the much longer

    Code:
    var i, ii;
    i= 0;
    ii = ary.length;
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,185
    Thanks
    80
    Thanked 4,453 Times in 4,418 Posts
    I'm going to nitpick a little here.

    Code:
    You can separate statements using commas
    Not true.

    You can use commas to separate expressions.

    It might *look* like you are using commas to separate statements when you do things such as
    Code:
        i= 0, ii = ary.length;
    but technically those are expressions. They *look* like statements, but that's because the assignment operators (= in this case) can be used in any expression, unlike many other languages where they can only be used in assignment statements.

    For example, in JavaScript (and Java and C and C++ and C#, but not in Pascal and BASIC and SQL and...) you can do things like this:
    Code:
         if ( ( a = b ) > c )
    or
         while ( ( counter += increment ) < limit )
    and the assignment (assign the value of b to the a variable, or assign the sum of counter and increment to counter) can and does take place. Not legal in all languages.

    Anyway, even in JavaScript you can't do such things as
    Code:
         a = 17, while ( a < 30 ) { ... }
    You must, indeed, use a semicolon between statements, not a comma. [Or omit the semicolon and let JavaScript figure out the statement boundaries. A horrible practice, in my never overly humble opinion.]

    But a comma between expressions is perfectly legal.

    I know, I know. It's a pretty fine point. And assignments *look* like statements. But technically they aren't. It's just that assignment expressions can be used *as* a statement in JavaScript.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    It might *look* like you are using commas to separate statements when you do things such as
    Code:
        i= 0, ii = ary.length;
    but technically those are expressions.
    Agreed - I was just trying to keep things simple for the beginners who don't know the difference between a statement and an expression since with that particular example simply replacing the comma with a semi-colon would convert the expressions into statements (just as long as that is the complete code (without var on the front or anything else that is intended to apply to each expression).
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,185
    Thanks
    80
    Thanked 4,453 Times in 4,418 Posts
    Yes, it's definitely true that there are places where using a semicolon between expressions will wipe you out, whereas the comma works great.

    I did say I was nit-picking. I hope that beginners will understand that such nit-picking is indeed beyond their concern at this point. This was more an extension of your correcting Goos' statements and impressions. Goos should know better, given the code he is exhibiting.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •