Created
October 4, 2015 08:49
-
-
Save leolux/c794fc63d9c362013448 to your computer and use it in GitHub Desktop.
Object-Oriented jQuery Plugin skeleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Source: http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html | |
//Author: Hector Virgen | |
//Date: August 23, 2010 | |
(function($) { | |
var MyPlugin = function(element, options) { | |
var elem = $(element); | |
var obj = this; | |
var settings = $.extend({ | |
param: 'defaultValue' | |
}, options || {}); | |
// Public method - can be called from client code | |
this.publicMethod = function() { | |
console.log('public method called!'); | |
}; | |
// Private method - can only be called from within this object | |
var privateMethod = function() { | |
console.log('private method called!'); | |
}; | |
}; | |
$.fn.myplugin = function(options) { | |
var element = $(this); | |
// Return early if this element already has a plugin instance | |
if (element.data('myplugin')) return element.data('myplugin'); | |
// pass options to plugin constructor | |
var myplugin = new MyPlugin(this, options); | |
// Store plugin object in this element's data | |
element.data('myplugin', myplugin); | |
return myplugin; | |
}; | |
})(jQuery); | |
//Usage: | |
//var myplugin = $('#myElement).myplugin(); | |
//myplugin.publicMethod(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment