Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write jquery chainable functions for local using?

How to write chainable functions but do not pollute $.fn ? Write functions only for using inside my plugin. Is it possible?

$('.myclass').makeSomething().andOneMoreFunction().andLast();

It is correct approach?

UPD. The best solution in my case is extension method:

String.prototype.getMyLength = function(){return this.length;}

And now I can apply this function to any string like this:

var mystring = "test";
mystring.getMyLength();

Or

"teststring".getMyLength()

And make it chainable:

String.prototype.getMe = function(){return this;}
"string".getMe().getMe().getMe().getMe().getMe();

Thanks for answers!

like image 337
Roman Bats Avatar asked Feb 22 '13 16:02

Roman Bats


2 Answers

You can chain all you want. If you define a $.fn yourself it is important that you return this at the end of you function.

If you want to write some javascript yourself you can also chain! It just depends on what you return. So if you return some other object, you can chain on from that object. The return value is used for this.

Example

var obj = {
    test : function(){ 
        alert("Y"); 
        return this; 
    },
    test2 : function(){ 
        alert("2"); 
        return this; 
    }
}
obj.test().test2(); // And so on since it returns this

jQuery Plugin API

$.fn.test = function(){
    var methods = {
        method0 : function(){
            alert("method0");
            return this;
        }
    };
    return methods;
}
var api = $("obj").test(); // Returns methods
api.method0(); // Calling a function from the returned methods.
// OR
$("obj").test().method0();

Above function is not jQuery chainable anymore. So you can't use the $("obj").test().addClass("test") because you return your own API!

like image 185
Niels Avatar answered Sep 23 '22 07:09

Niels


You can avoid pollution by using the first parameter of your plugin's function to specify the method of choice; for instance

(function () {
    var o = { // object holding your methods
        'bar': function () {console.log('bar', this); return this;},
        'foobar': function () {console.log('foobar', this); return this;}
    };
    $.fn.foo = function (method /*, args*/) {
        return o[method].apply(
            this,
            Array.prototype.slice.call(arguments, 1) // pass your args
        );
    };
}());

and then

$('something').foo('bar').foo('foobar');
/*
bar, thisobj
foobar, thisobj
*/

This way you keep access to the jQuery object as normal, too.

like image 30
Paul S. Avatar answered Sep 19 '22 07:09

Paul S.