Last active
August 29, 2015 14:13
-
-
Save andycole/325dd3970bec3fc27825 to your computer and use it in GitHub Desktop.
AMD jQuery Plugin Template
This file contains 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
// MYPLUGIN CLASS DEFINITION | |
// ========================== | |
(function (factory) { | |
if (typeof define === 'function' && define.amd) { | |
define(['jquery'], factory); | |
} else { | |
factory(window.jQuery); | |
} | |
}(function ($) { | |
var MyPlugin = function (element, options) { | |
'use strict'; | |
var myplugin = this; | |
this.$element = $(element); | |
this.options = $.extend({}, MyPlugin.defaults, options); | |
this.$element.on('mouseover', function () {myplugin.publicMethod();}); | |
}; | |
MyPlugin.defaults = { | |
someVar: 50, | |
nextVar: 'Some text' | |
}; | |
MyPlugin.prototype = { | |
myAttribute: 'value', | |
_privateMethod: function () { | |
//Does something private. | |
}, | |
publicMethod: function () { | |
//Does something public. | |
} | |
}; | |
$.fn.myplugin = function (option) { | |
var args = [].splice.call(arguments, 1); | |
return this.each(function () { | |
var $this = $(this), | |
data = $this.data('myplugin'), | |
options = typeof option === 'object' && option; | |
if (!data) { | |
$this.data('myplugin', (data = new MyPlugin(this, options))); | |
} else if (typeof option === 'string') { | |
data[option].apply(data, args); | |
} | |
}); | |
}; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment