forked from jquery-boilerplate/jquery-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.widget-factory.bridge.boilerplate.js
91 lines (73 loc) · 2.7 KB
/
jquery.widget-factory.bridge.boilerplate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*!
* jQuery UI Widget factory "bridge" plugin boilerplate
* Author: @erichynds
* Further changes, additional comments: @addyosmani
* Licensed under the MIT license
*/
// a "widgetName" object constructor
// required: this must accept two arguments,
// options: an object of configuration options
// element: the DOM element the instance was created on
var widgetName = function( options, element ){
this.name = "myWidgetName";
this.options = options;
this.element = element;
this._init();
}
// the "widgetName" prototype
widgetName.prototype = {
// _create will automatically run the first time this
// widget is called
_create: function(){
// creation code
},
// required: initialization logic for the plugin goes into _init
// This fires when your instance is first created and when
// attempting to initialize the widget again (by the bridge)
// after it has already been initialized.
_init: function(){
// init code
},
// required: objects to be used with the bridge must contain an
// 'option'. Post-initialization, the logic for changing options
// goes here.
option: function( key, value ){
// optional: get/change options post initialization
// ignore if you don't require them.
// signature: $('#foo').bar({ cool:false });
if( $.isPlainObject( key ) ){
this.options = $.extend( true, this.options, key );
// signature: $('#foo').option('cool'); - getter
} else if ( key && typeof value === "undefined" ){
return this.options[ key ];
// signature: $('#foo').bar('option', 'baz', false);
} else {
this.options[ key ] = value;
}
// required: option must return the current instance.
// When re-initializing an instance on elements, option
// is called first and is then chained to the _init method.
return this;
},
// notice no underscore is used for public methods
publicFunction: function(){
console.log('public function');
},
// underscores are used for private methods
_privateFunction: function(){
console.log('private function');
}
};
// usage:
// connect the widget obj to jQuery's API under the "foo" namespace
// $.widget.bridge("foo", widgetName);
// create an instance of the widget for use
// var instance = $("#elem").foo({
// baz: true
// });
// your widget instance exists in the elem's data
// instance.data("foo").element; // => #elem element
// bridge allows you to call public methods...
// instance.foo("publicFunction"); // => "public method"
// bridge prevents calls to internal methods
// instance.foo("_privateFunction"); // => #elem element