Elod P Csirmaz’s Blog: October 2009

21 October 2009

A solution to broken 'this' when using methods as handlers in JavaScript OO

Perhaps you've already run into the problem that 'this' does not refer to the instance the method belongs to when one tries to use a method in an object outside the context of the object, like as an event handler. To take an example using jQuery:

function myClass(){
this.myvar="Hello";
this.myfunc=function(){
alert(this.myvar);
}
}
var obj=new myClass();
$(document).ready(obj.myfunc);

The code would not work as 'this' inside event handlers in jQuery always refers to the HTML element that fired the event. An easy way of solving this is to take advantage of closures, that is, the fact that a function retains its execution context. In other words, a variable defined outside the function is accessible even if the function is called outside its original context, via a reference. Amend the above script as follows:

function myClass(){
var me=this;
this.myvar="Hello";
this.myfunc=function(){
alert(me.myvar);
}
}
var obj=new myClass();
$(document).ready(obj.myfunc);

This would work as expected. During instantiation, the variable 'me' becomes a reference to the object being defined. As it is in the execution context of myClass::myfunc, it remains accessible, and thus the current object can be reached from within the function even without using 'this'.

14 October 2009

Diff Tool for Source Codes

I've been trying to search for a diff tool with readable HTML output to create reports on scripts and source codes under development. As I couldn't find one that met my needs, I created one: it's accessible at http://www.epcsirmaz.co.uk/?q=diff.

Some features:
- Hosted on-line, there is no need to install anything locally
- Easily readable HTML-based output with the two versions displayed side by side
- Wrapped long lines
- Specially adapted to text files: disregards whitespaces and treats empty lines specially

As the script is specially adapted to detect individual insertions and removals, it is not an implementation of the longest common subsequence problem -- although I might amend the script later.

Hope you'll find this useful!

10 October 2009

jQuery UI Draggable and IE8

An interesting fact: if you use jQueryUI draggable on two DIVs one of which is contained in the other, interesting things can happen. If you start to drag the inner DIV, Firefox and Opera behaves as expected: only the inner DIV starts to follow the mouse. IE, however, starts to drag both DIVs, which results in the parent DIV following the mouse, and the child DIV moving twice as far as the mouse from the original location.

A solution to this problem can be to bind an event handler to the mousedown event on the child DIV, and stop event propagation.