How to extend jQuery plugins?

I want to create a jQuery plugin to migrate a chart component. It will have features like addLineSerie or addBarsSerie. Then I want to create other plugins that extend this feature to add new functionality or overwrite what you need, but you can still call the original functions of the plugin.

I started with the approach below. This seems to work, but as I understood later, I cannot name the original “parent” implementation (if I create an instance of myB, I cannot name myA.goA2).

(function($){
    $.fn.myA = function(settings) {
        this.goA = function() {alert("goA: "+settings);};
        this.goA2 = function() {alert("goA2: "+settings);};
        return this;
    };
})(jQuery);

(function($){
    $.fn.myB = function(settings) {
        this.myA(settings);
        this.goA2 = function() {alert("goA2B: "+settings);};
        this.goB = function() {alert("goB: "+settings);};
        return this;
    };
})(jQuery);

I have 2 questions:

  • Is this approach right, or should I do it differently?
  • How to make the parent and the "child" the same instance, but still get the opportunity to call the implementation of the "parent"?

Thank.

+5
1

, - :

(function($) {
    $.fn.myA = function(settings) {
        this.goA = function() {
            alert("goA: " + settings);
        };
        this.goA2 = function() {
            alert("goA2: " + settings);
        };
        return this;
    };
})(jQuery);

(function($) {
    $.fn.myB = function(settings) {
        this.myA = $.fn.myA(settings);
        this.goA2fromA = function() {
            this.myA.goA2();
        };
        this.goA2 = function() {
            alert("goA2B: " + settings);
        };
        this.goB = function() {
            alert("goB: " + settings);
        };
        return this;
    };
})(jQuery);

$(document).ready(function() {
    var a = $('#one').myA({});
    var b = $('#one').myB({});
    a.goA2();
    b.goA2fromA();
});

EDIT: myA , . :

http://jsfiddle.net/PqQgs/4/

+1

All Articles