-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent-core.coffee
More file actions
275 lines (251 loc) · 10.1 KB
/
component-core.coffee
File metadata and controls
275 lines (251 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# Component.coffee is a minimal library for when classical inheritence isn't
# enough. Components may be known to you as *traits*, or *mixins*, or something
# else. Multiple inheritance, like in Python, is also somewhat similar.
#
# The idea is to make your *code* conform to the problem space, instead of trying
# to shoehorn the problem into some design pattern. Here's a concrete example.
# ### Classical Inheritance
# You're making a game. The class structure, using classical inheritance is
# shown below (arrows denote a parent→child relationship). You have objects
# which respond to gravity, like the player. You also have bullets, which
# kill, but don't respond to gravity. Bullet and Player share common code
# related to rendering and position, and everything is amazing.
#
# +-----------+ +------------+
# | *Physics* | | *Player* |
# +----------+ +--->|-----------+--->|------------|
# | *Base* | | | Gravity | | Controls |
# |----------| | +-----------+ | Walk |
# | Render +---+ +------------+
# | Position | | +----------+
# +----------+ | | *Bullet* |
# +--->|----------|
# | Kill |
# +----------+
# Now you want to add missiles which respond to gravity. You could do this:
#
# +-----------+ +------------+
# | *Physics* | | *Player* |
# +----------+ +--->|-----------+--->|------------|
# | *Base* | | | Gravity | | Controls |
# |----------| | +-----------+ | Walk |
# | Render +---+ +------------+
# | Position | | +----------+
# +----------+ | | *Weapon* | +----------+
# +--->|----------|--+-->| *Bullet* |
# | Kill | | +----------+
# +----------+ |
# | +-----------+
# | | *Missile* |
# +-->|-----------|
# | Gravity |
# +-----------+
#
#
# Bullets and missiles can share the code for killing, awesome. But there's
# a glaring issue here though: *code for gravity is duplicated*. You probably
# copy-pasted it, didn't you? Now any changes to gravity have to be done in two
# places simultaneously, *yuck*.
# How about this?:
#
# +----------+ +-----------+ +------------+
# | *Base* | | *Physics* | | *Player* |
# |----------+--->|-----------+--->|------------|
# | Render | | Gravity | | Controls |
# | Position | +-----+-----+ | Walk |
# +----------+ | +------------+
# |
# v +----------+
# +----------+ +-->| *Bullet* |
# | *Weapon* | | +----------+
# |----------|+--+
# | Kill | | +-----------+
# +----------+ +-->| *Missile* |
# +-----------+
#
# Gravity isn't repeated, so it's good now, right? Except that bullets now have
# code related to gravity. This is workable if that gravity code is never
# called, but that's rather crufty. It's also makes the code harder to read,
# since inspecting the inheritance chain would have you believe that bullets do
# react to gravity.
# ### Components
# Let's see how using components solve this problem. The following diagram
# shows the same code, but using components instead of classical inheritance:
#
# +----------+ +-----+-----+
# +----------+ | *Base* | | *Physics* |
# | *Bullet* |<---|----------|--->+-----------|
# +----------+ | Render | | Gravity |
# ^ | Position | +-----+-----+
# | +----------+ |
# | |
# | +---------------+
# | | |
# +----+-----+ v v
# | *Weapon* | +-----------+ +------------+
# |----------+--->| *Missile* | | *Player* |
# | Kill | +-----------+ |------------|
# +----------+ | Controls |
# | Walk |
# +------------+
#
# Physics includes Base functionality, as in classical inheritance. But now
# Missile borrows functionality from both the Physics and Weapon components.
# Bullets can take just the Base and Weapons components, without Physics, and
# Player needs to include only the Physics component.
# Let's see what this looks like in code. JavaScript follows, but in
# *CoffeeScript*, this looks like:
#
# # This object literal becomes part of the prototype of
# # the final component, as for Physics/Weapon/Player.
# # So the usual caveats apply: mainly not putting per-
# # instance variables into the prototype chain.
# Base =
# render: ->
# console.log "Rendering at (#{@x}, #{@y})!"
# init: (@x = 0, @y = 0)->
# console.log "@init() called"
#
# Physics = component Base,
# gravity: (v = 1)-> @y += v
#
# Weapon =
# kill: (obj)->
# delete GameObjects[obj.id]
#
# Missile = component Physics, Weapon
# Bullet = component Base, Weapon
#
# Player = component Physics,
# walk: -> @x += 2
# gravity: ->
# console.log "Demonstrating super"
# @super(3)
# update: ->
# @walk()
# @gravity()
# @render()
#
# me = new Player(10,10) # @init() called
# me.update()
# me.render() # Rendering at (12, 13)!
# Or the same thing in *JavaScript*:
#
# // This object literal becomes part of the prototype of
# // the final component, as for Physics/Weapon/Player.
# // So the usual caveats apply: mainly not putting per-
# // instance variables into the prototype chain.
# Base = {
# render: function() {
# console.log(
# "Rendering at (" + this.x + ", " + this.y + ")!"
# );
# },
# init: function(x, y) {
# this.x = x != null ? x : 0;
# this.y = y != null ? y : 0;
# return console.log("this.init() called");
# }
# };
#
# Physics = component(Base, {
# gravity: function(v) {
# v = (v != null) ? v : 1;
# this.y += v;
# }
# });
#
# Weapon = {
# kill: function(obj) {
# return delete GameObjects[obj.id];
# }
# };
#
# Missile = component(Physics, Weapon);
# Bullet = component(Base, Weapon);
#
# Player = component(Physics, {
# walk: function() {
# return this.x += 2;
# },
# gravity: function() {
# console.log("Demonstrating super");
# this.super(3);
# },
# update: function() {
# this.walk();
# this.gravity();
# this.render();
# }
# });
#
# me = new Player(10, 10); // this.init() called
# me.update();
# me.render(); // Rendering at (12, 13)!
# # Code
# This is the public interface to component.coffee.
#
# *Parameters*: Any number of object literals or components (constructors)
# *Returns*: A component. This is just a constructor function with a prototype
# made up of the given objects/components. Use this constructor
# function with the `new` keyword as usual. You can set your own
# constructor with an `init` property, like so:
#
# MyComponent = component({
# init: function(){ this.x = 2 }
# })
# myInstance = new MyComponent
# myInstance.x == 2
#
# Note that instances of components have built-in `extend` and `super` methods.
# The documentation for these functions is at `ComponentBase`. But here's an
# example, continuing from the above example:
#
# myInstance.extend({y: function(){ return 2 }})
# myInstance.extend({y: function(){ return 3 + this.super() })
# myInstance.y() == 5
component = (components...)->
# Create a base object to serve as the returned component's prototype
comp = new ComponentBase
comp.extend components...
# A constructor function is returned as the component, ensuring that
# object instantiation from the component is fast via `new`.
# A user-defined `init` property is used as the constructor, if available.
F = comp.init ? ->
F.prototype = comp
# Give F the same extension interface as a `new MyComponent()`
F.extend = -> ComponentBase::extend.apply(F.prototype, arguments)
return F
# Instances of `ComponentBase` serve as prototypes for components. This gives
# instances of components access to `@extend` and `@super` methods.
ComponentBase = ->
# `extend` copies properties from the arguments passed in to `this`
#
# *Parameters*: Any number of object literals or components (constructors)
# *Returns*: null
ComponentBase::extend = (components...)->
for c in components
# Allows extension using both object literals and other components.
# Like this: `x = component(a:1); y = component(x, b:2)`
c = c.prototype ? c
# Copy all key/value pairs from given object to `this`. Create a `super`
# property for functions that will be overwritten, except `extend`/`super`
for key, val of c
continue unless c.hasOwnProperty key
if this[key] and typeof val is 'function' and not /extend|super/.test key
old = this[key]
this[key] = val
this[key].super = old
else
this[key] = val
return null
# Use this by calling `this.super(arg1, arg2)` in a component's function.
# The corresponding function that it overwrote earlier will be called.
#
# *Parameters*: Arguments to be passed on
# *Returns*: Whatever the overwritten function returns
ComponentBase::super = ->
@super.caller.super.apply(this, arguments)
# Export in case CommonJS is being used
if module?.exports?
module.exports = component