core error

Chaining in Javascript

Posted on: 13/07/2011

What

Chaining is the ability to call methods ‘inside’ other methods. JQuery makes this quite straightforward ( $(‘#text1’).removeClass(‘newPost’).addClass(‘oldPost’); ) but it can also be done in plan Javascript.

Why

Chaining is quite handy for controlling the flow of your application or for have a better control on the scope of your variables (which is always a pain in Javascript).

How

You just need to remember that in javascript you can return not only values, but also functions:

  posAbsolute("myid").html("you made my day");  

  function posAbsolute(elementId){
      var node = document.getElementById(elementId)

       return{
           html : function(content){
               node.innerHTML = content;
           }
       };
  }

The scope of the variables inside the function named html is now safe

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


    • Justin Cooney: Great comic, this made me laugh!
    • Justin Cooney: Interesting, I didn't know about the Google App Engine, I'm glad I found your article on it!

    Categories

    %d bloggers like this: