Give javascript some love

I am reading the nice titled book “javascript – the good parts” and i guess most people needed a long time, like me, to understand what javascript is. Maybe this is the reason why so many javascript-code is a hack. Spaghetti tastes good, but…

We are using jquery as our js-libary and a “normal” bit a javascript code looks like this:

jQuery(document).ready(function() {
    $("#same_id").click(function(){
        action1
        action2
    });
    $("#another_id").click(function(){
        action3
    });
});

i think nobody would ever do this in a “real” programming language. Why not make it expressive and structure it a bit?

var Homepage = {
   init: function(){
      $("#same_id").click(Homepage.doA)
      $("#same_id").click(Homepage.doB)
   },
   doA: function(){
      action1
      action2
   },
   doB: function(){
      action3
   }
}
jQuery(document).ready(function() {
  Homepage.init()
});

What do you think?

P.S. This code is probably not 100% valid :-)

1 Response to “Give javascript some love”

  1. Aljoscha Says:
    I tend to disagree. The first version is more concise and clear. I would even suggest, it was the clear intention of the jQuery developers to make you write your code exactly like this.

Leave a Reply