evillemez/javelin — pull request #57 by evillemez (2014-06-07 01:28:17+00:00)
Title: Event handling & simple reference solution

Closes #19
Closes #55
Closes #56

## References ##

This implements a fairly simple solution to the "weak" reference problem. If a component needs to reference another entity other than its self, it can do so like this:

```js
var targetRef = engine.instantiate('mygame.prefab').reference;
//...
if (targetRef.entity) {
//...do something...
}
```

This way, when an entity is destroyed, it's reference will be nulled out. I think given how javascript works, this is about the best I can do, unfortunately.

## Events ##

New events are added for entity hierarchy changes:

* `entity.parent` - When an entity has a new parent.
* `entity.child.add` - When an entity receives a new child
* `entity.child.remove` - When an entities child is removed

Some entity-related events have changed names:

* `engine.create` is now `entity.create`
* `engine.destroy` is now `entity.destroy`

Most importantly, components now register callbacks on the entity - not themselves. For example:

Old way:

```js
javelin.component('mygame.component', [], function(entity, game) {
this.$on('entity.update', function() { /*...do stuff ...*/ });
});
```

New way:

```js
javelin.component('mygame.component', [], function(entity, game) {
entity.on('entity.update', function() { /*...do stuff ...*/ });
});
```

This simplifies behavior, and is probably somewhat more intuitive - components are responsible for providing custom APIs for your game, and/or registering behaviors on entity instances. The downside is that because callbacks are stored in the entity, a component can't be removed - however this was already the case for other reasons, so it's not really a compromise.