Introducing Protowidget
May 29th, 2006I’d like to introduce a new JavaScript/Ajax framework that my company is creating. We’re calling it Protowidget because it uses Prototype and does things with widgets. And yes, we know it’s 2006 and this is something like the 800th Ajax framework released this year. We think this one is new and different, though (of course, every parent thinks their baby is beautiful). It is being created out of real needs while building applications for customers and is helping us create better stuff. Please note that this is just a preview. Not everything works like it should or has been tested to the degree we would like. In particular, under certain circumstances, the library leaks memory. We know what needs to change to fix this but haven’t gotten to it yet.
Motivation
The best tools are born out of pain. With regard to existing Ajax tools, here is a brief list of some of the pain we felt and wanted to address:
- ID-madness: Some frameworks (ie. Dojo) attempt to avoid this, but most make the primary coupling point between JavaScript and HTML be the ID attribute. While many have shown this to work, it is somewhat offensive to have only one flat namespace. This becomes an especial problem when trying to create repeating sections or scoped, re-usable components. Since the namespace is flat, it also causes problems when one component needs to logically interact with others.
- Non-standard UI construction: At the end of the day, HTML+CSS is a pretty good tool for laying out web-based UIs. We can certainly come up with better representations, but they are rarely as rich and they are typically not designer friendly. Despite a lot of other great ideas, I consider this to be OpenLaszlo’s primary failing. Other frameworks which take the Swing-esque approach of coding the UI programatically by assembling objects are even weaker.
- No client side model: Years ago someone co-opted the long standing MVC design pattern and claimed that having servlets and views somehow conformed to the pattern. Maybe it technically does, but it is certainly not in the spirit of MVC as seen in real client-side apps. Today, we have an interesting inversion going on where most people think that the web-MVC (type II or whatever) pattern is classical-MVC. We need to be applying some classical-MVC principles to our client-side interfaces. Otherwise, we will end up with as much spaghetti as can be found in an old-school VB6 app. OpenLaszlo and Flex with their pervasive property bindings provide the building blocks for this type of development. Few others do.
- Separating form from function: This is the holy grail, and likely no tool will ever get 100% there. The idea is that the visual layout and characteristics should be specified out-of-band from the code that manipulates it. A good framework should have well-defined intersection points where the visual bits mix and interact with the programmatic bits.
In the end, we really liked the simplicity of Prototype, the widgets/templates from Dojo and the event-based property binding support from OpenLaszlo/Flex.
Example
Here is a link to one of the Protowidget test pages. It’s not much to look at and certainly doesn’t do anything that can’t be done elsewhere. The magic is in how it is done, and that is what the rest of this post will focus on. http://www.rcode.net/stage/trunk/protowidget/test/bind_test.html
This current version has been verified on Firefox 1.5 and Internet Explorer 6.
Widgets
As the name implies, Protowidget is based on widgets. While some widgets are provided (and more will come in the future), Protowidget’s primary focus is on providing a rich environment for constructing complicated widgets.
A widget is always bound to an HTML element. This will typically be a div, but can really be anything (depending on the widget). We take the Dojo approach of leveraging custom attributes in order to do all of the wiring. This has the advantage of letting us bypass the ID-madness when it comes to hooking widgets to DOM elements. Here is an example:
<span pw.type='Text' pw.text='#{`[currentSection].model.title`}'></span>
This HTML declaration tells Protowidget to bind the span to the built-in Text widget. It further sets up a property binding so that the text property will be bound to the value of model.title on the current section (this example came from the Accordian title-bar template so the currentSection reference is an Accordian.SectionWidget in this context).
Hierarchy
Widgets exist in a hierarchy of parent-child relationships that typically mirrors the HTML DOM elements that they are defined on. Each widget has a parent and may have an id property. A widget may also be attached to another widget (most likely its parent) by name. All of these techniques work together to create a navigable tree of widgets. Unlike the global IDs on HTML elements, Protowidget id’s are scoped such that they can only be resolved by children in the hierarchy. That is, referencing a widget by id from a child widget is equivilent to saying “Give me the widget arbitrarily up the parent chain with a given ID.” The top-level widget is a special singleton which logically is defined on the body element and has an id of “root”.
Properties
The Widget class extends the built-in Component class which is responsible for managing properties. Properties formalize the mechanism for changing an Object’s state by providing getters/setters, change event support, and hooks that are called when values are set or read. Every Component sub-class will have a getProperty and setProperty method which are the primary entry points for generically manipulating properties. There are convenience facilities available for declaring appropriate getters and setters for properties as well.
Attributes
In addition to properties, widgets also maintain the concept of attributes by exposing the methods getAttribute and setAttribute. These methods define the mechanism for navigating to other properties within the widget tree. Arbitrary parts of the tree can be referenced by specifying an attribute path such as ‘a.b.c’. There is a special escape in the attribute syntax: If a component of the path is surrounded by square brackets, it will resolve to the parent with the given id (between the brackets). While a similar effect could be achieved by using a correct number of parent references (ie. ‘parent.parent.parent.textField’), using the ID notation is more straight-forward: ‘[commonParent].textField’.
Bindings
Bindings represent the mechanism whereby any property can be bound to any other property in the tree. If the value of the source property (or the path to the source property) changes, the bound target property will be updated. This has already been illustrated by the Text example above. As with OpenLaszlo, the binding is done with a special syntax, called a Binding Expression in Protowidget. This is done by specifying the value of a property with the syntax:
#{someJavaScriptExpression}
where someJavaScriptExpression is any legal JavaScript expression. The trick that makes it so powerful is the special escape sequence using the backtick characters (`). Any sub-expression within the JavaScript expression may have a backtick reference. The attribute path to another part of the tree can be specified within the backticks and its value will be placed into the expression at evaulation time. The entire binding will be evaluated when first established and whenever the value or path of a contained backtick expression changes.
Here are some examples:
#{`[root].product.name`}- References the product.name property on the root widget.#{`[commonParent].position` * 50}- Evaluates to the position property on the commonParent parent multiplied by 50.
Special Support for Element Attributes
The DomWidget class (which most general-purpose widgets will extend) has special support for initializing properties on its instances. Any attributes defined on the attached HTML element which starts with ‘pw.’ and is not a standard Protowidget attribute will result in the corresponding property being set on the widget (as was illustrated with the pw.text HTML attribute above). These can either be literal Strings of binding expressions.
The DomWidget class treats style attributes specially by performing some conversions (ie. from numbers to pixel units) and allowing them to be specified on the element with HTML attributes of the form ‘pw.style.left’. It would be silly to define constant styles this way, but it is very useful for binding styles. For example:
pw.style.left="#{`[commonParent].position` * 50}"pw.style.color="#{`[section].status`=='success' ? 'green' : 'red'}"
Templates
When doing JavaScript programming “in the large”, it quickly becomes necessary to break visual parts out of the main flow. Protowidget defines a template mechanism whereby external HTML sources (which can contain widget declarations) can be loaded and instantiated within an application. We will not go into this facility in depth here, but suffice it to say that it forms the basis for some of the other capabilities presented later.
Models
Protowidget defines two general purpose model classes which may be extended as necessary to define intra-application models. By attaching these non-visual models to the root widget as properties, the model properties can be bound to any widget property in the application.
Model.Data
The Model.Data class is intended to be a generic container for properties. The intent is that it will provide advanced serialization/deserialization support for synchronizing with a server.
Model.DataList
The Model.DataList class provides an event wired List/array abstraction. It defines the following methods: getLength, itemAt, add, remove, and removeAt. In addition, it defines an ‘onlist’ event which is fired any time the list is structurally modified.
DataListRepeater
Protowidget defines an abstract BaseDataListRepeater class which provides the low-level machinery for keeping an arbitrary Model.DataList (specified by setting the ‘list’ property) in sync with visual widgets that represent each list item. The algorithm is efficient and can handle arbitrary changes to the backing list while only creating corresponding visual widgets for new entries.
The TemplateDataListRepeater extends BaseDataListRepeater so that a given template (specified by the template property) is instantiated for each element in the list. In the example, this is what is driving the numbered list that rotates every second.
Accordian
Protowidget defines an Accordian widget and related model. The widget is bound to the model and tracks all changes to the overall model or any of its sections. Internally, the accordian widget is a subclass of BaseDataListRepeater and illustrates the power of an abstract model-bound repeater widget.
An Accordian.Model consists of a Model.DataList of Accordian.SectionModel instances and an activeSection property. Each Accordian.SectionModel has the following properties: enabled, active, title, caption, owner and template. Most of these control the title bar. The template property specifies a template to be instantiated as the section’s content. All properties (including template) are bound, so that any changes take effect immediately. Display of the title bar is driven by a template and CSS class names have been defined such that all visual characteristics are externalized in the accordian.css file. All visual characteristics of the accordian can be changed by modifying the CSS file or the title bar template. This even goes so far as to allowing additional information or behaviour to be defined in the title bar by binding widget properties in the title bar template to user-defined properties on the SectionModel.
Here is an example of creating an Accordian model:
var accordian=new Protowidget.Types.Accordian.Model();
Protowidget.RootWidget.setProperty('accordian', accordian);
var section;
section=new Protowidget.Types.Accordian.SectionModel(
accordian, ‘Section 1′, ‘In Progress’);
section.setTemplate(’user!section1.html’);
accordian.sections.add(section);
section=new Protowidget.Types.Accordian.SectionModel(
accordian, ‘Section 2′, ‘Complete’);
section.setTemplate(’user!section2.html’);
accordian.sections.add(section);
section=new Protowidget.Types.Accordian.SectionModel(
accordian, ‘Section 3′, ‘Success’);
section.setTemplate(’user!section3.html’);
accordian.sections.add(section);
And here is how an accordian would be instantiated based on that model:
<div pw.type='Accordian.Widget'
pw.model='#{`[root].accordian`}'
style='width: 75%; height: 300px; overflow: hidden;'>
</div>
Logger
A Logger library is also included with Protowidget (see src/logger.js). We intend to break this out separately because it has no ties to Protowidget. While looking at the example, press ‘ALT-L’ to see the log window (if it doesn’t work, click somewhere in the document and try again to make sure the document has focus). The logger will automatically popup on errors. The primary methods to interact with it are Log.debug, Log.info, Log.warn and Log.error. Each of those methods also exposes an ‘enabled’ property for checking whether that log level is turned on. For example:
if (Log.debug.enabled) Log.debug("Hello World");
This would typically only be used if generating the log message was an expensive operation.
Final Thoughts
Releasing this work to the public is really just a preview at this point. Protowidget does things differently than a lot of other libraries, and we think it does them better. Please let us know what you think. Either post comments to our forums or email us personally.
The current snapshot of the source is here. Since the template system uses XmlHttpRequest, any examples must be run within a web server. There is a ruby script in the root directory that will start a web server to serve from the current directory (by default on port 2000).
Introducing Protowidget
May 29th, 2006I’d like to introduce a new JavaScript/Ajax framework that my company is creating. We’re calling it Protowidget because it uses Prototype and does things with widgets. And yes, we know it’s 2006 and this is something like the 800th Ajax framework released this year. We think this one is new and different, though (of course, every parent thinks their baby is beautiful). It is being created out of real needs while building applications for customers and is helping us create better stuff.
Head over to the dedicated page on this blog to find out more.
About
May 22nd, 2006Hi, my name is Terry Laurenzo and I own Redcode Technologies. This blog is mostly about technology and contains a mixture of work and non work-related content.