Skip to content

Instantly share code, notes, and snippets.

@frostney
Created January 20, 2013 16:07
Show Gist options
  • Save frostney/4579523 to your computer and use it in GitHub Desktop.
Save frostney/4579523 to your computer and use it in GitHub Desktop.
A bit more advanced Entity-Component-Model (based on https://gist.github.com/4402499) which takes advantage of the dynamicness of JavaScript by adding the prototype and property functions from components to the entity itself.
# Example 1
# Adding properteies to Component instances
console.log '--- Example 1 ---'
comp1 = new Component('comp1')
comp1.test = -> console.log 'Comp1'
comp2 = new Component('comp2')
comp2.test = -> console.log 'Comp2'
myEntity = new Entity('myEntity')
myEntity.add(comp1)
myEntity.add(comp2)
myEntity.test?()
# Example 2
# Instantiating Components and adding functions to the prototype
console.log '--- Example 2 ---'
class Component1 extends Component
test: -> console.log 'Component 1'
class Component2 extends Component
test: -> console.log 'Component 2'
myComponent1 = new Component1()
myComponent2 = new Component2()
myOtherEntity = new Entity('myOtherEntity')
myOtherEntity.add(myComponent1)
myOtherEntity.add(myComponent2)
myOtherEntity.test?()
# Example 3
# Represeting components as simple objects
console.log '--- Example 3 ---'
myCoolEntity = new Entity()
myCoolEntity.add(
name: 'First component'
test: -> console.log('Testing: First component')
)
myCoolEntity.add(
name: 'Second component'
test: -> console.log('Testing: Second component')
)
myCoolEntity.test?()
###
This implementation of an entity-component model takes advantage of the
dynamicness of JavaScript.
Prototype and property functions that have been added to components can
be directly accessed from the entity
###
class Entity
functionList = {}
constructor: (@name = @constructor.name) ->
@components = {}
functionList = {}
add: (component) ->
return @ unless component
componentName = component.name
componentInstance = @components[componentName]
unless componentInstance
componentInstance = component
componentInstance.register?()
for key, value of componentInstance
continue if key is 'constructor'
#console.log "#{key}: #{value}"
if typeof value is 'function'
functionList[key] = [] unless functionList[key]
functionList[key].push(value)
unless @[key]
@[key] = ((key) ->
(->
#console.log functionList[key]
functions.apply(this, arguments) for functions in functionList[key]
@)
)(key)
@
remove: (componentName) ->
if @components[componentName]
@components[componentName].unregister?()
delete @components[componentName]
@
render: ->
for key, value of @components
value.render?()
@
update: (dt) ->
for key, value of @components
value.update?(dt)
@
class Component
constructor: (@name = @constructor.name) ->
register: ->
unregister: ->
render: ->
update: (dt) ->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment