Crafty.c
public void Crafty.c(String name, Object component)
- name
- Name of the component
- component
- Object with the components properties and methods
Creates a component where the first argument is the ID and the second is the object that will be inherited by entities.
There is a convention for writing components.
- Properties or methods that start with an underscore are considered private.
- A method called
initwill automatically be called as soon as the component is added to an entity. - A method with the same name as the component is considered to be a constructor and is generally used when you need to pass configuration data to the component on a per entity basis.
Example
Crafty.c("Annoying", {
_message: "HiHi",
init: function() {
this.bind("EnterFrame", function() { alert(this.message); });
},
annoying: function(message) { this.message = message; }
});
Crafty.e("Annoying").annoying("I'm an orange...");
WARNING:
in the example above the field _message is local to the entity. That is, if you create many entities with the Annoying component they can all have different values for _message. That is because it is a simple value, and simple values are copied by value. If however the field had been an object or array, the value would have been shared by all entities with the component because complex types are copied by reference in javascript. This is probably not what you want and the following example demonstrates how to work around it:
Crafty.c("MyComponent", {
_iAmShared: { a: 3, b: 4 },
init: function() {
this._iAmNotShared = { a: 3, b: 4 };
},
});

@craftyjs
#crafty@freenode.net
google groups
louis@craftyjs.com
github