Friday, August 7, 2009

Using Prototype and YUI

Using prototype and YUI

There are many reasons why you might use prototype.js with yui. You may be moving to Yahoo User Interface, or vice versa, or you may just prefer some flexibility. Whatever the reason, there are some good points to using the two together. I have pointed out several times on this blog and Practical Prototype that I personally prefer this method. I use YUI for the widgets, and use prototype for setting up classes, events, and other low level organization. Let's see a quick example:

MySimpleDialog = Class.create({
  initialize: function($div_id, $options){
    this.defaults = {
      width: "20em",
      fixedcenter: true,
      visible: false,
      draggable: true
    Object.extend(this.defaults, $options || {});
    this.dialog = new YAHOO.widget.SimpleDialog($div_id, this.defaults);
  render: this.dialog.render,

  setTitle: function($title){ this.dialog.setHeader($title);}
  setBody: function($body){ this.dialog.setBody($body); }

To initialize a new MySimpleDialog all we have to do now is:

var $mydialog = new MySimpleDailog('my div id');

Notice we do not have to send any options to the SimpleDialog constructor, and if we had, they would override the defaults. To get Fancy, we could create a Template class to be used by our "overridden" setBody method. Keeping things generic helps you to reuse scripts.

No comments: