themirror
themirror

Reputation: 10287

JS: Turn single-argument function into chainable

What's the simplest way to take any 1-argument function and make it chainable onto another function?

So this would look something like...

red = function (target) {target.$.style.backgroundColor("red");}
blue = function (target) {target.$.style.backgroundColor("blue");}
body = $("body");
red(body);
#body is now red
makeFunctionChainable(blue);
body.blue()
#body is now blue

Upvotes: 0

Views: 56

Answers (3)

OrfeasZ
OrfeasZ

Reputation: 71

If I understand what you're trying to do, you can actually define a global extension to the Object prototype which would allow you to call red() or blue() on any object.

Object.prototype.red = function()
{
    $(this).css('background-color', 'red');
    return this;
};

Object.prototype.blue = function()
{
    $(this).css('background-color', 'blue');
    return this;
};

And then you can use it like so:

$('body').red().blue();

I should note that this is bad practice it you only want to use that with jQuery elements.
Instead, you should write a jQuery extension for it.

Upvotes: 1

bobbor
bobbor

Reputation: 141

Chaining is only possible if the element returned by function1 has function2

example

var obj = {
  red: function(target) {target.$.style.backgroundColor("red");return this;},
  blue: function(target) {target.$.style.backgroundColor("blue");return this;}
};

and use

obj.red(body).blue(body);

Upvotes: 0

qwertynl
qwertynl

Reputation: 3933

You can do chaining by returning something that will make it chainable, like this

var setColors = (function(){
    var target = null;
    var setTarget = function(t) {
        target = t;
        return this;
    };
    var color = function (colorChange) {
        target.$.style.backgroundColor(colorChange);
        return this;
    };
    return {setTarget: setTarget, setColor: color};
})();

var body = $("body");
//sets the red than blue immediately 
setColors.setTarget(body).setColor('red').setColor('blue');

Upvotes: 0

Related Questions