1

I have the following code:

function doSomething(str){
    return str+="a";
}

function anotherFunction(str){
    return str+="b";
}

_.mixin({
    doSomething:doSomething,
    anotherFunction:anotherFunction
});

I want to use multiple functions together in one line, but I can't manage to work:

var output=_("startingtext").doSomething().anotherFunction();

I managed to make it work using _.chain, but I am not sure if chain should be used because in their example they are using with objects and stuff, so I really doubt this is the way to go for string manipulation.

Sorry, I am new to underscore :(, any help is appreciated.

1
  • you would have to wrap any output again with _(), eg return _(str+"a"); in the first function and equivalent in the second. Commented Jan 31, 2012 at 19:54

2 Answers 2

1

_.chain() is exactly the way to go.

In Javascript, everything is an object. Including a string. You were doing it right the first time. _.chain() wraps your string in an object that can be passed forward, chain-style, and unpacked at the end with a call to value().

Sign up to request clarification or add additional context in comments.

Comments

0

An option would be to wrap the return value with _() and call .value() at the end of the chain:

function a(v) {
    return _(v + 'a');
}

function b(v) {
    return _(v + 'b');
}

_.mixin({a:a, b:b});
_('some-text').a().b().value(); // returns some-textab

Not my favourite option though.

The accepted answer in this question has an alternative, but it still needs to call .value() at the end. If you really want to get rid of it, you'd have to add functions to the String.prototype

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.