forked from jquery-boilerplate/jquery-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.highly-configurable.plugin.boilerplate.js
68 lines (55 loc) · 1.88 KB
/
jquery.highly-configurable.plugin.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
/*
* 'Highly configurable' mutable plugin boilerplate
* Author: @markdalgleish
* Further changes, comments: @addyosmani
* Licensed under the MIT license
*/
// Note that with this pattern, as per Alex Sexton's, the plugin logic
// hasn't been nested in a jQuery plugin. Instead, we just use
// jQuery for its instantiation.
;(function( $, window, document, undefined ){
// our plugin constructor
var Plugin = function( elem, options ){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
// This next line takes advantage of HTML5 data attributes
// to support customization of the plugin on a per-element
// basis. For example,
// <div class=item' data-plugin-options='{"message":"Goodbye World!"}'></div>
this.metadata = this.$elem.data( 'plugin-options' );
};
// the plugin prototype
Plugin.prototype = {
defaults: {
message: 'Hello world!'
},
init: function() {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options,
this.metadata);
// Sample usage:
// Set the message per instance:
// $('#elem').plugin({ message: 'Goodbye World!'});
// or
// var p = new Plugin(document.getElementById('elem'),
// { message: 'Goodbye World!'}).init()
// or, set the global default message:
// Plugin.defaults.message = 'Goodbye World!'
this.sampleMethod();
return this;
},
sampleMethod: function() {
// eg. show the currently configured message
// console.log(this.config.message);
}
}
Plugin.defaults = Plugin.prototype.defaults;
$.fn.plugin = function(options) {
return this.each(function() {
new Plugin(this, options).init();
});
};
//optional: window.Plugin = Plugin;
})( jQuery, window , document );