How to write jquery chainable functions for local use?

How to write function chains but not pollute $ .fn? Write functions only for use inside my plugin. Is it possible?

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

The right approach?

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

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

And now I can apply this function to any string, for example:

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

or

"teststring".getMyLength()

And make it chained:

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

Thanks for answers!

+5
source share
3 answers

You can cling to whatever you want. If you define yourself $.fn, it is important that you are return thisat the end of your function.

javascript , ! , . , - , . .

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

API- jQuery

$.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();

jQuery. $("obj").test().addClass("test"), API!

+5

, , ;

(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
        );
    };
}());

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

jQuery .

+3

a.foo(), foo this, a. .

, a.foo() , return d .

, this.

Then it a.foo()returns to a, and (a.foo()).bar()becomes equivalent to a call a.foo(), and then calls a.bar()... i.e. chain operations on a!

$.fnnot particularly magical; it just uses the above logic the same way you do.

0
source

All Articles