josephg / Chipmunk-js

Port of slembcke/Chipmunk-Physics to Javascript
http://dl.dropbox.com/u/2494815/demo/Joints.html
536 stars 59 forks source link

regarding Collision Callback #11

Closed Wu-Hao closed 11 years ago

Wu-Hao commented 11 years ago
        box1.shape.setCollisionType(3);
        box2.shape.setCollisionType(8);
        Space.addCollisionHandler(3,8, null, function(){alert(1)});

Alert is called

But real world application requires a target for function to call

        box1.shape.setCollisionType(3);
        box2.shape.setCollisionType(8);

        box1.hi = "hello";
        box1.sayHi = function(){
            alert(this.hi);
        };

        Space.addCollisionHandler(3,8, null, box1.sayHi);

you get undefined, because what ever object calling "sayHi()" it does not have .hi attribute

Any idea how to fix this? In cocos2d-html5, our callback handler function accepts a function with a target like

X.addCallback(target, obj.func)
josephg commented 11 years ago

Using Object.bind() is the obvious choice.

Space.addCollisionHandler(3,8, null, box1.sayHi.bind(box1));

Or:

Space.addCollisionHandler(3,8, null, function() { box1.sayHi(); });
kirbysayshi commented 11 years ago

Just a small clarification, it's not actually Object.bind, but rather Function.prototype.bind. bind is a method on the Function prototype, not the Object prototype. Object inherits its prototype from Function.

It doesn't change @josephg's answer, in that bind is the right choice, but if someone doesn't know what bind is, then it's important to start with accurate information... which I hopefully provided :)

josephg commented 11 years ago

Thanks - I'm so used to coffeescript where you just use the fat arrow operator.

kirbysayshi commented 11 years ago

Yeah, I understand. It's definitely one of JS's awesome-powers that can also shoot you in the foot.

For what it's worth, I'm very glad you didn't write this library in coffee-script!