jQuery: plugin factory method

by gabrieleromanato

HTML

<div id="test"></div>

CSS

#test {
    margin: 1em;
    background: silver;
}

JavaScript

var PluginFactory = {

    init: function(options, elem) {
        this.options = $.extend({}, this.options, options);

        this.elem = elem;
        this.$elem = $(elem);


        this._build();

        return this;
    },
    options: {
        name: 'Test'
    },
    _build: function() {
        this.$elem.html('<p>' + this.options.name + '</p>');
    },
    method: function(msg) {

        this.$elem.append('<p>' + msg + '</p>');
    }
};

if (typeof Object.create !== 'function') {
    Object.create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}


$.plugin = function(name, object) {
    $.fn[name] = function(options) {
        return this.each(function() {
            if (!$.data(this, name)) {
                $.data(this, name, Object.create(object).init(
                options, this));
            }
        });
    };
};




$.plugin('test', PluginFactory);
$('#test').test({
    name: 'Gabriele'
});
var instance = $('#test').data('test');
instance.method('method()');