Created
March 26, 2014 17:24
-
-
Save IOZ/9788604 to your computer and use it in GitHub Desktop.
jquery plugin pattern
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
if (typeof Object.create !== "function") { | |
Object.create = function (obj) { | |
function F() {} | |
F.prototype = obj; | |
return new F(); | |
}; | |
} | |
(function ($, window, document) { | |
var Plugin = { | |
init : function (options, el) { | |
var _super = this; | |
this.$elem = $(el); | |
this.options = $.extend({}, $.fn.Plugin.options, _super.$elem.data(), options); | |
this.userOptions = options; | |
this.decorate(); | |
this.text(); | |
}, | |
decorate : function (color) { | |
var _super = this; | |
var color = color || _super.options.color; | |
this.$elem.css({ | |
background: color | |
}); | |
}, | |
text : function (text) { | |
var text = text || this.options.text; | |
this.$elem.html(text); | |
} | |
}; | |
$.fn.Plugin = function (options) { | |
return this.each(function () { | |
if ($(this).data("init") === true) { | |
return false; | |
} | |
$(this).data("init", true); | |
var plugin = Object.create(Plugin); | |
plugin.init(options, this); | |
$.data(this, "Plugin", plugin); | |
}); | |
} | |
$.fn.Plugin.options = { | |
color: '#ff0000', | |
text: 'Hello' | |
}; | |
}(jQuery, window, document)); | |
$(function(){ | |
$('.plugin').Plugin(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment