Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - stop chain of objects methods without error

Tags:

javascript

oop

We have some Foo object

var Foo = function() {

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

So it allows us to do some foo.bar().bar().bar().bar(); chain.

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

So how to make all chain return false without errors whan any of its 'rings' return false?

FIDDLE

like image 593
OPOPO Avatar asked Mar 05 '13 09:03

OPOPO


1 Answers

You will have to change the return type of bar. I suggest to create a sort of null object for that purpose and add a finalization method at the end of the chain which 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 fiddle example I did not use the finalize method but instead gave the null object a show method. Otherwise you still would have false.show() at the end:

Fiddle

like image 179
Fabian Schmengler Avatar answered Oct 12 '22 14:10

Fabian Schmengler