JS - methods for stopping a chain of objects without errors

We have some object foo

var Foo = function() { this.bar = function(bazinga) { if (bazinga) {return this;} else {return false;} } this.show = function() { alert('bar'); } }; 

Thus, this allows us to chain foo.bar().bar().bar().bar(); .

But if in the middle of the chain bar () returns false, then the next bar () attempts will cause an error that undefined has no method bar() whitch is a thing.

So, how to make the whole chain return false without errors if any of its β€œrings” returns false?

Fiddle

+6
source share
3 answers

You will need to change the return type in the row. I suggest creating a null object for this purpose and adding a completion method at the end of the chain that returns false for the null object:

 var Foo = function() { var nullFoo = function() { this.finalize = function() { return false; } this.bar = function() { return this; } } this.finalize = function() { return this; } this.bar = function(bazinga) { if (bazinga) {return this;} else {return new nullFoo();} } this.show = function() { alert('bar'); } }; foo.bar().bar().bar().bar().finalize(); 

For your example script, I did not use the finalize method, but instead gave the null object the show method. Otherwise, you will still have false.show() at the end:

Fiddle

+3
source

This is what you want: http://jsfiddle.net/c24w/MXgzx/5/

JavaScript:

 var Foo = function() { var returnValue = true; this.bar = function(bazinga) { returnValue = returnValue && bazinga; return this; } this.show = function() { alert('bar'); return returnValue; } }; 
0
source

Method chains can be a little dangerous. It all depends on the dependencies.

When using a chain of methods, it is useful to keep track of the objects returned by each part of the chain.

If they are not all the same, for example, they are not all lines, then it’s nice to break the chain into separate statements. Or perhaps select them in a separate function.

Say you have a chain, for example

 somearray.pop().getATagWrapper().getTag().setSrc("http://www.stackoverflow.com") 

Implicit chain dependencies: Array, Object1, TagWrapper, Tag, String

Now the function you wrote is now associated with all of these objects, and any change to them can potentially destroy the chaos with your code.

Where we look

 someString.trim().substr(12).trim().concat("with awesome") 

Everything deals only with the String object.

See Law of Demeter for more details.

0
source

All Articles