HTML and CSS Reference
In-Depth Information
if(idx != -1) {
this.entity.activeComponents.splice(idx,1);
}
this.debind();
if(this.destroyed) this.destroyed();
}
});
The base component class has only two main responsibilities: to handle being added to an entity and to
handle being removed from that entity. When the component is added to an entity (which is done in the init
constructor) the component does five things:
1. It sets a property so that it can refer back to the entity.
2. It extends the entity with new properties from its extend attribute.
3. It adds itself to the entity as a property under its name. (So, for example, the sword component would
be accessible via entity.sword .)
4. It also adds itself to the entity's list of active components.
5. It calls the added method on the component to set up any post-initialization requirements like listen-
ers.
The Q.Component class extends from the Q.Evented object, so it can bind and be bound to.
When a component is destroyed, it needs to do the reverse, which amounts to removing any extensions by
removing properties that match the keys of the extend object from the entity. Next, it needs to destroy the prop-
erty named after the component from the entity and remove the entry from the active components list. Finally,
it calls debind to remove any event handlers it has bound and calls the custom destroyed() handler if one
is defined.
The last piece for the component system is the Q.GameObject class, which inherits from Q.Evented
and is responsible for adding and removing components. The Q.GameObject class is the base class from
which all active game objects, such as sprites, inherit from.
Add the definition of Q.GameObject in Listing 9-16 to the spot at the bottom of quintus.js before the
final return.
Listing 9-16: Q.GameObject definition
Q.GameObject = Q.Evented.extend({
has: function(component) {
return this[component] ? true : false;
},
add: function(components) {
components = Q._normalizeArg(components);
if(!this.activeComponents) { this.activeComponents = []; }
for(var i=0,len=components.length;i<len;i++) {
var name = components[i],
comp = Q.components[name];
if(!this.has(name) && comp) {
var c = new comp(this);
this.trigger('addComponent',c);
}
}
 
 
Search WWH ::




Custom Search