Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Created March 29, 2012 08:09
Show Gist options
  • Save jakejscott/2234812 to your computer and use it in GitHub Desktop.
Save jakejscott/2234812 to your computer and use it in GitHub Desktop.
Best jQuery plugin example yet
$(function() {
var $document = $(document);
$document.trigger('domloaded', $document);
$('.someselector').load('/my/url', function(nodes) {
$document.trigger('ajax_loaded', nodes);
});
});
;(function ($, doc, win) {
"use strict";
var name = 'js-widget';
function Widget(el, opts) {
this.$el = $(el);
this.$el.data(name, this);
this.defaults = {
optionA: 'someOption',
optionB: 'someOtherOption'
};
var meta = this.$el.data(name + '-opts');
this.opts = $.extend(this.defaults, opts, meta);
this.$header = this.$el.find('.header');
this.$body = this.$el.find('.body');
this.init();
}
Widget.prototype.init = function () {
var self = this;
this.$header.on('click.' + name, '.title', function (e) {
e.preventDefault();
self.editTitle();
});
this.$header.on('change.' + name, 'select', function (e) {
e.preventDefault();
self.saveTitle();
});
};
Widget.prototype.editTitle = function () {
this.$header.addClass('editing');
};
Widget.prototype.saveTitle = function () {
var val = this.$header.find('.title').val();
// save val to database
this.$header.removeClass('editing');
};
Widget.prototype.destroy = function () {
this.$el.off('.' + name);
this.$el.find('*').off('.' + name);
this.$el.removeData(name);
this.$el = null;
};
$.fn.widget = function (opts) {
return this.each(function () {
new Widget(this, opts);
});
};
$(doc).on('dom_loaded ajax_loaded', function (e, nodes) {
var $nodes = $(nodes);
var $elements = $nodes.find('.' + name);
$elements = $elements.add($nodes.filter('.' + name));
$elements.widget();
});
})(jQuery, document, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment