Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend jQuery plugins?

I want to create a jQuery plugin to wrap a chart component. It will have functions like addLineSerie or addBarsSerie. Then I want to create other plugins that extend this one to add new functionality or overwrite what's needed but still be able to call the original plugin functions.

I started with the approach below. It kind of works but, as I realized later, I can't call the original "parent" implementation (if I create an instance of myB, I can't call 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);

So I have 2 questions:

  1. Is this approach right or I should be doing this in a different way?
  2. How do make the "parent" and the "child" be the same instance a yet get to call the "parent's" implementation?

Thank you.

like image 703
Xay Avatar asked Nov 14 '22 23:11

Xay


1 Answers

This seems about right, but to accomplish cross-plugin behavior can't you just do this:

(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: fixed the call to myA and added the call that one would make. Check out the working fiddle:

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

like image 183
Milimetric Avatar answered Dec 11 '22 00:12

Milimetric