【问题标题】:Examples of multiple instance javascript widgets (on same page)?多个实例 javascript 小部件的示例(在同一页面上)?
【发布时间】:2010-08-24 19:16:11
【问题描述】:

对于这个快速的问题,我深表歉意,但我希望看到一些允许在同一页面中出现多个实例的示例小部件。 (关于这种技术的文章也很好!)

Digg 的小部件允许这样做 (http://about.digg.com/downloads/widgets),但我不知道还有其他小部件。

你呢?

谢谢。

【问题讨论】:

    标签: javascript widget instance


    【解决方案1】:

    查看任何YUI widgets。例如,一个页面上有多个 YUI 增强的buttons

    使用每个实例的数据创建多个实例

    基本技术如下所示。

    由于调用程序使用 new,因此会为每个小部件创建一个 Larry.widget 对象的新实例。因此,每个小部件都有自己的独立对象“this”,并使用它来存储每个实例的数据。

    同时,对象的原型拥有函数。所以所有的小部件共享相同的功能,但有自己的数据集。

    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. 
    }         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多