多实例JavaScript小部件的示例(在同一页上)?
问题描述:
为快速问题道歉,但我想看到一些示例窗口小部件,允许在同一页面的多个实例。 (关于这种技术的文章也会很好!)多实例JavaScript小部件的示例(在同一页上)?
Digg的小部件允许这个(http://about.digg.com/downloads/widgets),但我不知道任何其他人。
是吗?
谢谢。
答
请参阅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://*.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.
}