Drip #69: Observer Pattern help?

28 views
Skip to first unread message

Andrew Rattana

unread,
Oct 8, 2014, 3:44:31 PM10/8/14
to js-drip-d...@googlegroups.com
Hey, just wondering on drip #69: Implementing the observer pattern, on the batman.batsignal method you used batman.defeatSupervillain instead of using this."property" as you do in the jimGordon object. Just wondering why and if you do use this.defeatSupervillain, how do you get it to work properly.

Thanks!

(function () {
    var batman = {
        defeatSupervillain: function (villain) {
            console.log("Batman handily defeats " + villain.name);
        },
        batSignal: function (villain) {
            batman.defeatSupervillain(villain); // <- why not this.defeatSupervillain
        }
    };

    jimGordon.registerObserver(batman.batSignal);
})();

Joshua Clanton

unread,
Jan 26, 2015, 3:11:18 PM1/26/15
to js-drip-d...@googlegroups.com
Hi Andrew,

Sorry it has taken me so long to get back to you. New little addition to the family had me derailed for a while. :-)

The reason I used `batman` instead of `this` is because the value of `this` depends on how the function is called. If you try using `this` in the example above, you'll see that you get an error when `jimGordon.notifyObservers` is called. Simplified example:

Try running the following in your browser console.

var obj = {
    fun
: function () {
        console
.log(this);
   
}
};

obj
.fun();
// => Object { fun: obj.fun() }

var fun = obj.fun;

fun
();
// => Window

Another solution would be to to use Function#bind as explained here: http://adripofjavascript.com/blog/drips/creating-bound-functions-with-function-bind.html

Hope that helps!

Josh Clanton
Reply all
Reply to author
Forward
0 new messages