Creating extensible Prototype Widgets

Justin Palmer shows how to avoid "bloat in widgets" with respect to Prototype. Widgets walk a fine line between abstractions and implementations. Implementation, in this case, is a practical solution chosen to perform a given function. The problems with widgets occur when the widget author walks too far in one direction, or worse, walks an […]

Justin Palmer shows how to avoid "bloat in widgets" with respect to Prototype.

Widgets walk a fine line between abstractions and implementations. Implementation, in this case, is a practical solution chosen to perform a given function. The problems with widgets occur when the widget author walks too far in one direction, or worse, walks an outward spiral covering both directions. Both choices lead to script bloat and complexity thats hard to manage. You no longer have a simple solution for a defined problem, you have a complex solution for a variety of problems. The good news is there are ways to avoid both the bloat and complexity.

Building our SuperBox
We’re gonna build a utterly useless SuperBox, and we realize that it could become quiet popular so we want to widgetize it. The only thing we want the SuperBox to do is to jump around on the screen when someone clicks it. Let’s look at how one might do that in Prototype:

 var SuperBox = Class.create(); SuperBox.prototype = { initialize: function(element, options) { this.element = $(element); this.options = Object.extend({ top: function(offset) { return Math.round(Math.random() * offset); }, left: function(offset) { return Math.round(Math.random() * offset); }, }, options || {}); this.setObservers(); }, setObservers: function() { Event.observe(this.element, 'click', this.onClick.bindAsEventListener(this)); }, onClick: function(event) { var element = Event.element(event); element.setStyle({top: this.options.top(200) + 'px', left: this.options.left(200) + 'px' }); } };
It’s probably ironic this could be done in far fewer lines of code, but the idea here is to provide a general level of abstraction that will result in less bloat in the future and make sure we don’t have to hack in additional functionality that ends up making it harder for users who just want the basics.
Continue for more info....

ajaxian

Creating extensible Prototype Widgets