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 4 of 4
  1. #1
    New to the CF scene
    Join Date
    May 2006
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Chaining methods

    Some javascript libraries like jquery or prototype can chain methods like so

    $('element').html('bla').show('fast');

    I can't figure out how this is done, does anyone have a simplified example?

    Thanks

  • #2
    Senior Coder
    Join Date
    Jul 2005
    Location
    New York, NY
    Posts
    1,084
    Thanks
    4
    Thanked 19 Times in 19 Posts
    That notation isn't chaining of methods.

    What is happening there is you have an object being returned by $. That object has a method called html, which is being called. That method returns an object that has the method show, which is being called. Expanded it looks like:

    var x = $('element');
    var y = x.html('blah');
    y.show('fast');

    But because $ returns a pointer, there's no reason to store it in x:

    var y = $('element').html('blah');
    y.show('fast');

    But the same is true for html, it returns a pointer to an object, why store it?

    $('element').html('blah').show('fast');

    Hope that clears it up.

  • #3
    New to the CF scene
    Join Date
    May 2006
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Well, you can do :

    $('element').html('bla').show('fast');
    $('element').show('fast').html('bla');

    so the order of the functions doesn't matter. There are also no duplicate functions.

  • #4
    Senior Coder
    Join Date
    Jul 2005
    Location
    New York, NY
    Posts
    1,084
    Thanks
    4
    Thanked 19 Times in 19 Posts
    You'll have to look into the library your using, but based on the syntax rules of javascript, the object returned from $ must have both show and html methods for the statements you posted to be true.

    I assure you that your library cannot change the rules of the language, this is object notation, and those are methods being called on objects.


  •  

    Posting Permissions

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