Recent Weblogs

Links I like

prototype.js

I have been happily using prototype.js on all major Javascript development for a few months now and I will say it makes the language suck a whole lot less. Easy to use functions such as Event.element() and Element.addClassName() make browser inconsistancies and strange nuances a thing of the past. Those functions are nice for easy tasks but don't really change the way you code, just allows you to code less.

Function.bind with prototype.js

The creme of the crop for prototype.js is the combination of Class.create, Obect.extend and Function.prototype.bind. With those three assets the ability of inheritance and runtime composition is achievable with moderately aesthetic syntax. Let me attempt to explain what Function.bind is actually doing. When you've got a function and you execute its property bind which happens to be.. another function it returns an anonymous function with your parameters that were sent to the bind function all pre concatenated to the argument scope. Typically you only send one paramter to this method which is the object you wish to "own" the method when it is executed. But what happens if you send two arguments to the bind method. Well then the second argument shows up as the first element when the function is actually executed (strange huh). Just think of bind as returning a function shell which allows you to maintain your scope of "this" in class structures.

Function.bind and determined

So lets say you want to use Event.observe for a click event.

  Event.observe(obj, "click", this.handleClick.bindAsEventListener(this));
  

So we'll receive the event as the first parameter, always.. its just the nature of bindAsEventListener. What happens now if an element is placed inside that object and is clicked. Well you'll still catch the event but e.target is now that nested element and not the object you bound to, "oh ok well i have e.currentTarget"... in FF but IE has no support for the currentTarget when working with this event Model(Thanks MS, hate you) Don't worry we can accomodate for inabilitiies..again. As previously stated all parameters sent to the bind method become part of the argument chain when the function is executed. so we can add the object to the argument scope when we bind its event listener as such

  Event.observe(obj, "click", this.handleClick.bindAsEventListener(this, obj));
  

Now when the function is called the object will be the second argument in the chain, because bindAsEventListener always puts the event argument first.

Comments are Disabled.