Wrong event scope in Raphael.js (and jQuery)

Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web.
While playing around with this nice SVG JavaScript library Raphaël.js, I stumbled upon an issue with the event scope. Raphael doesn’t allow event handlers to run in any specific scope. This is a problem when you want to work with its event system ‘eve()’ in combination with classes. The problem is that ‘this’ inside the called method, doesn’t refer to the class instance. There is an easy workaround for it, something I remembered from the good ol’ ActionScript2 days. Just store the scope and use it when the event is triggered.
MyClass.function() {
  var scope = this;
  eve.on("DoSomethingEvent", function(event) {
    scope.doSomething(event);
  }  
}

MyClass.prototype {
  doSomething: function(event) {
    // use original 'this'
  }
}
jQuery has the same issue. You can use the same workaround in jQuery, but you can also use the jQuery.proxy() method.
$("#button").click($.proxy(function () {
     // use original 'this'
 },this));

Wednesday, December 14, 2011   ()