Tuesday, May 24, 2011

Bind jQuery event handlers for this object CoffeeScript


Bind jQuery event handlers for this object CoffeeScript 

Friends have told me that the rich domain objects rarely does so using jQuery to improve performance in web pages. I myself have always loved dynamic JavaScript as a language rich first and something for the second DOM. So most of my client-side JavaScript is an object-oriented robust approach similar to Ruby. This is the main reason they have used Prototype.js for so long.

Since both jQuery and Rails CoffeeScript announced as the default in version 3.1, I decided it was time to start learning them. I had always known that jQuery linked keyword is in the event handlers to the DOM object. Something you are totally confused and unacceptable for someone working on their own objects to encapsulate behavior. Today I found two ways to deal with my problem, one way and one way CoffeeScript jQuery. First a code example.


class MyObject
  
  constructor: ->
    @myDomElement = $('#myDomElement')
    @._initBehavior


  handler: (event) ->
    console.log(this)
    false


  _initBehavior: ->
    $(window).resize @handler


jQuery ->
  window.myObject = new MyObject();


Here is a simple class using methods CoffeeScript. Is initialized with a static property this.myDomElement a DOM element on the page with the id "myDomElement." Then, you assign an event handler to the event of resizing the window and records this on the road. Simple things, the only problem is that the registered object will not be an instance of MyObject, but the raw DOM element, in this case the window object. One way to fix this is to use jQuery function as a proxy for


_initBehavior: ->
  $(window).resize jQuery.proxy(@handler,this)




This works but seems a little tedious for me and can clog up your initialization code of the event. The other way is to use the arrow operator CoffeeScript fat. An extract from the project page explains it well.

The fat arrow => can be used both to define a function, and linked to the current value of this, on the spot. This is useful when using callback libraries based on how Prototype or jQuery, to create a repeater function to pass each, or the event handler functions for use with link. Created with the arrow functions of fat are able to access the properties where they are defined. 
So all we have to do is change - of> = for any of our callbacks or event handlers, and now this is our own object and not the DOM element. Hot Damn! 


class MyObject
  
  constructor: ->
    @myDomElement = $('#myDomElement')
    @._initBehavior


  handler: (event) =>
    console.log(this)
    false


  _initBehavior: ->
    $(window).resize @handler


jQuery ->
  window.myObject = new MyObject();




1 comment:

Sara Arundale said...

You have done a great job much appreciate your work. Keep sharing its really helpful to me and hope other also.