Alex Rivera | Logout

How to detect the end of a method chain in JavaScript?

Asked 2013-01-02T14:11:20.533
11

Firstly and most importantly I'm trying to detect the end call of a method chain. I would also like to devise a way to detect how many methods "in" or "down" an object chain I am within my method calls in a method chain.

For instance, in the plugin I'm writing:

var result = $("#someDiv").myPlugin.foo().bar()._foo()._bar();

Say the method is currently executing in .bar() I would like to know that I'm 2 methods down the chain.

The reason I need to abstract this information in some manner is so when I reach the last method in the chain I can return a result instead of the plugin object thus breaking the chain at that point for the sake of gaining access to our data in the 'result' variable.

Edit
Report

1 Answer

1

It isn't possible to determine if a call is the last instance in a chain when determining the return value, and here is why:

var result = $("#someDiv").myPlugin.foo().bar()._foo()._bar();

foo returns myPlugin on which bar is called which returns myPlugin on which _foo is called which returns myPlugin on which _bar is called.

So effectively, when _foo returns its value (myPlugin), it is before that value is utilized. Unless _foo is psychic, it can't know what will happen next.

As pointed out in your comments, your best bet is to have some "end" method, like results().

Another suggestion would be to pass a handler in to myPlugin that gets called to set the value using setTimeout(..., 0). Have a value in myPlugin that foo, bar, _foo, and _bar all set. Let's call it returnValue. Modify myPlugin to accept a method as it's only parameter. Let's call that handler. This method's first argument will contain the value. Inside of myPlugin, before your return, do:

window.setTimeout(function () {
    handler(returnValue);
}, 0);

Since setTimeout's function parameter will not be called until execution is finished, it will contain the last value set for returnValue - effectively the value set by the last call in the chain. I'd consider this the closest option to what you are trying to achieve, since the developer doesn't have to worry about which of his methods are called last.

answered 2013-01-02T14:30:22.020

Your Answer