Skip to content

Instantly share code, notes, and snippets.

@lravik
Forked from lsmith/SamplePlugin.js
Created May 27, 2010 07:06
Show Gist options
  • Save lravik/415557 to your computer and use it in GitHub Desktop.
Save lravik/415557 to your computer and use it in GitHub Desktop.
/*
* An example of
* 1. Using the YUI 3 module system to encapsulate a custom class for reuse
* 2. Creating a Plugin class
* 3. Using Y.Base.create to generate the class
*/
// YUI.add(
// "dash-separated-module-name",
// function (Y) { Y.MyModule = ...; },
// version_string,
// module_metadata);
// NOTE YUI.add is a *static* method on the YUI global
// Create a module named sample-plugin
YUI.add('sample-plugin', function(Y) {
// Signature of Y.Base.create(..) is
// Y.Base.create(
// name_string, e.g. "camelCase"
// ClassToExtend, e.g. Y.Base or Y.Widget
// array_of_extension_Classes, e.g. [Y.WidgetStdMod]
// obj_of_prototype_members_and_methods, (see below)
// static_members_and_methods); (see below)
// @returns a class constructor function
// Create Y.Plugin.SamplePlugin class from Y.Base with no extensions
Y.namespace('Plugin').SamplePlugin = Y.Base.create("sample", Y.Base, [], {
// Prototype properties and methods
// (Prefer attributes over properties for) Public instance properties
foo: "default value for instance.foo property (public)",
// Underscore prefix (quasi) private properties for common internal refs
_type : null,
initializer : function(config) {
// Code that runs at instantiation (constructor code) goes here
},
somePublicMethod: function () {
var val = this.get('myAttribute');
this.set('myAttribute', "new value");
// etc
},
_quasiPrivateMethod: function () {
// publicly available, but implementers shouldn't access directly
}
}, {
// Static members and methods
// Namespace applied to the plugged instance to house the plugin API.
// e.g. host.plug(Y.Plugin.SamplePlugin); host.sample.somePublicMethod()
NS : "sample",
// Instance attributes made available via instance.get('attributeName')
// instance.set('attributeName', "new value");
ATTRS : {
attributeName : {
value : "default value",
validator: Y.Lang.isString
// see also setter, getter, writeOnce, readOnly, etc
},
anotherAttribute : {
value : null,
setter : function(val) {
if (val === true) {
return "a new value to assign to the attribute";
} else if (val % 2) {
// don't update attribute value
return Y.Attribute.INVALID_VALUE;
}
return val; // is stored as the new value
}
}
}
});
}, 'v0.0.1' , { requires : [ 'plugin' ] });
(elsewhere)
YUI().use('sample-plugin', function (Y) {
...
instance.plug(Y.Plugin.SamplePlugin, { someAttribute: "this value" });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment