You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A plugin constructor uses Prototypal pattern. It needs to have a ._init() method used for its main logic.
// plugin constructor// accepts two argments, element and options objectfunctionNiceGreeter(element,options){this.element=$(element);this.options=$.extend(true,{},this.options,options);this._init();}// defaults for plugin optionsNiceGreeter.prototype.options={greeting: 'hello',recipient: 'world'};// main plugin logicNiceGreeter.prototype._init=function(){varmessage=this.getMessage();this.element.text(message);};// getter methodNiceGreeter.prototype.getMessage=function(){returnthis.options.greeting+' '+this.options.recipient;};
Usage
Bridget can make this constructor work as a jQuery plugin. The namespace is the plugin method - $elem.namespace().
// convert constructor to jQuery plugin$.bridget('niceGreeter',NiceGreeter);// now the constructor can be used as a jQuery pluginvar$elem=$('#elem');$elem.niceGreeter();// >> h1 text will be 'hello world'// set options$elem.niceGreeter({greeting: 'bonjour',recipient: 'mon ami'});// >> text will be 'bonjour mon ami'// access constructor instance via .data()varmyGreeter=$elem.data('niceGreeter');
Getter methods can still be used. For jQuery objects with multiple elements, getter methods will return the value of the first element.
Package managers
Install with Bower 🐦: bower install jquery-bridget
Install with npm npm install jquery-bridget
Install with component: component install desandro/jquery-bridget