views:

17

answers:

1

Apologies for the quick question, but I'd like to see some sample widgets that allow multiple instances in the same page. (Articles about this technique would also be good!)

Digg's widget allows this (http://about.digg.com/downloads/widgets) but I don't know of any others.

Do you?

Thanks.

A: 

See any of the YUI widgets. Eg multiple YUI-enhanced buttons on a page.

Creating multiple instances with per-instance data

The basic technique is shown below.

Since the calling program uses new, a new instance of the Larry.widget object is created for each widget. So each widget has its own, separate object "this" and uses it for storing per-instance data.

At the same time, the object's prototype holds the functions. So all of the widgets share the same functions, but have their set of data.

Larry = {}; // Create global var
Larry.widget = function (options) {
  // create with new. Eg foo = new Larry.widget({an_option: true, id: "q_el"});
  // options: object with members:
  //   an_option
  //   id
  // Then call foo.xyz(); to get the widget to do xyz
  this.init(options);
};

Larry.widget.prototype = {
  constructor: Larry.widget,
  // Setting the constructor explicitly since we're setting the entire
  // prototype object. 
  // See http://stackoverflow.com/questions/541204/prototype-and-constructor-object-properties/541268#541268

  init: function(options) {
    this.id = options.id;
    this.an_option= options.an_option;

    this._function_a(); // finish initialization via a function.
  },  // remember that function init is a member of the object, so separate 
      // the functions using commas

  _function_a: function() {
     // This is a "private" function since it starts with _
     // Has access to "this" and its members (functions and vars)
     ....
  },

  xyz: function() {
     // This is a "public" function. 
     // Has access to "this" and its members (functions and vars)
     ...
  } // Note: NO TRAILING COMMA!
    // IE will choke if you include the trailing comma. 
}         
Larry K