Monday, October 18, 2010

Closures are cool, but

I've really getting into JQuery, Ajax, etc.

Closures have become a requirement for me.

Most of my Javascript code is written in OO style. I used objects to contain data returned from Ajax requests and have function that apply that to Dom Nodes etc.

What happens is that 99% of my callbacks are in basically calls to a function on an object.

What I typically do is set a variable = this to create closure to it. An anonymous function then calls a method against my objects.

me = this;
...click(function(evt){me.someFuncOnObj(evt)});

This works really well, except that it can get old.

What I'd really like all languages that are taking on closures to do is to combine them with object to create object closures. In addition being able to pass params into functions in would be cool without the need for a closure.

The syntax in JS might look like this.

....click ( &myObj.myFunc );

This would tell JS to call myFunc on myObj.

Options you could tell it to pass in parameters to this function.

....click(&myObj.myFunc{divId:'#myDiv'} );

The point here is that function will always get appeneded to its arguments like the parameter "divId". This allows for "generic" callbacks.

For now I'm thinking of just created a java function that does the trick.

function callBack(objArg,funcArg,paramsArg)
{
var obj = objArg;
var func = funcArg;
var params = paramsArg;

var thefunc = function(){
obj[funcArg](arguments);
}

return thefunc;

}


The problem here I need to pass the arguments along, but I'm sure I can figure that out.

......click ( callBack(myObj, 'myFunc', {sample:'test'} );

For now the function must be a string, but I suppose it could take a func pointer and find it in the obj.













No comments: