I've recently taken on a job where I have been required to use jQuery instead of my usual framework of choice - prototype. I've handled the transition well enough but one area of functionality has me befuddled - using object methods to handle events. I've been working around the problem but the workarounds are quite ugly.
An explanation. First I'll give the code as it would look in prototype myClass = Class.create({ this.element: null, this.initialize: function( element ) { this.element = element; element.observe('click', this.onClick.bindAsEventListener(this)); }, this.onClick: function(e) { // actions on click here. } }); Now I know how to build classes in javascript without prototype's Class library. I also know how to use late binding and prototype modifications to achieve what that library abstracts. The problem is how am I supposed to replicate bindAsEventListener? I've tried... myClass = function( element ) { // element is an element somewhere in the dom that this class will manage a behavior for. // Assume for the purposes of this example that it's already encapsulated in a jQuery object this.element = element; this.onClick = function() { // on click actions. } this.element.bind('click', this.onClick ); } If I run the code as above the meaning of 'this' is lost. Unfortunately this.element.bind('click', this.onClick ).apply(this); // more or less what .bindAsEventListener actually does. won't work - it causes jQuery to issue an error. So how is anyone supposed to use object methods to handle events, a cornerstone of object oriented programming? If I'm to continue using this framework I need to find a solution to this problem.