Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a Chaining Pattern like jQuery does? [duplicate]

How do I create a prefix like the one jQuery uses? For example, in jQuery I can use:

$(".footer").css('display', 'none');

and I'd like to enable a similar syntax, like this:

google('.footer').chrome('display', 'none');

I have searched Google for an answer, but couldn't find it.

like image 892
Iago Bruno Avatar asked Oct 16 '25 22:10

Iago Bruno


1 Answers

You have a detailed explanation here

But the right way to implement is show bellow:

var google = function(valor){
    var lalala = '3';

    this.chrome = function(valor){
        console.log(lalala + ' ' + valor);
        return this;
    }

    this.firefox = function(valor){
        console.log(lalala + ' ' + valor);
        return this;
    }

    console.log(valor);

    return this;
};

console.log('first call');
google('testando').chrome('stack');

console.log('second call');
google('testando').chrome('stack').firefox('test');

As you could see the key is to return the object itself on each function.

You could see the live code at jsbin.com

like image 122
Claudio Santos Avatar answered Oct 19 '25 12:10

Claudio Santos