-
Notifications
You must be signed in to change notification settings - Fork 1
/
crafty.js
8294 lines (7452 loc) · 223 KB
/
crafty.js
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Crafty v0.4.5
* http://craftyjs.com
*
* Copyright 2010, Louis Stowasser
* Dual licensed under the MIT or GPL licenses.
*/
(function (window, undefined) {
/**@
* #Crafty
* @category Core
* Select a set of or single entities by components or an entity's ID.
*
* Crafty uses syntax similar to jQuery by having a selector engine to select entities by their components.
*
* @example
* ~~~
* Crafty("MyComponent")
* Crafty("Hello 2D Component")
* Crafty("Hello, 2D, Component")
* ~~~
* The first selector will return all entities that has the component `MyComponent`. The second will return all entities that has `Hello` and `2D` and `Component` whereas the last will return all entities that has at least one of those components (or).
* ~~~
* Crafty(1)
* ~~~
* Passing an integer will select the entity with that `ID`.
*
* Finding out the `ID` of an entity can be done by returning the property `0`.
* ~~~
* var ent = Crafty.e("2D");
* ent[0]; //ID
* ~~~
*/
var Crafty = function (selector) {
return new Crafty.fn.init(selector);
},
GUID = 1, //GUID for entity IDs
FPS = 60,
frame = 1,
components = {}, //map of components and their functions
entities = {}, //map of entities and their data
handlers = {}, //global event handlers
onloads = [], //temporary storage of onload handlers
tick,
tickID,
noSetter,
loops = 0,
skipTicks = 1000 / FPS,
nextGameTick = (new Date).getTime(),
slice = Array.prototype.slice,
rlist = /\s*,\s*/,
rspace = /\s+/;
/**@
* #Crafty Core
* @category Core
* @trigger NewComponent - when a new component is added to the entity - String - Component
* @trigger RemoveComponent - when a component is removed from the entity - String - Component
* @trigger Remove - when the entity is removed by calling .destroy()
* Set of methods added to every single entity.
*/
Crafty.fn = Crafty.prototype = {
init: function (selector) {
//select entities by component
if (typeof selector === "string") {
var elem = 0, //index elements
e, //entity forEach
current,
and = false, //flags for multiple
or = false,
del,
comps,
score,
i, l;
if (selector === '*') {
for (e in entities) {
this[+e] = entities[e];
elem++;
}
this.length = elem;
return this;
}
//multiple components OR
if (selector.indexOf(',') !== -1) {
or = true;
del = rlist;
//deal with multiple components AND
} else if (selector.indexOf(' ') !== -1) {
and = true;
del = rspace;
}
//loop over entities
for (e in entities) {
if (!entities.hasOwnProperty(e)) continue; //skip
current = entities[e];
if (and || or) { //multiple components
comps = selector.split(del);
i = 0;
l = comps.length;
score = 0;
for (; i < l; i++) //loop over components
if (current.__c[comps[i]]) score++; //if component exists add to score
//if anded comps and has all OR ored comps and at least 1
if (and && score === l || or && score > 0) this[elem++] = +e;
} else if (current.__c[selector]) this[elem++] = +e; //convert to int
}
//extend all common components
if (elem > 0 && !and && !or) this.extend(components[selector]);
if (comps && and) for (i = 0; i < l; i++) this.extend(components[comps[i]]);
this.length = elem; //length is the last index (already incremented)
} else { //Select a specific entity
if (!selector) { //nothin passed creates God entity
selector = 0;
if (!(selector in entities)) entities[selector] = this;
}
//if not exists, return undefined
if (!(selector in entities)) {
this.length = 0;
return this;
}
this[0] = selector;
this.length = 1;
//update from the cache
if (!this.__c) this.__c = {};
//update to the cache if NULL
if (!entities[selector]) entities[selector] = this;
return entities[selector]; //return the cached selector
}
return this;
},
/**@
* #.addComponent
* @comp Crafty Core
* @sign public this .addComponent(String componentList)
* @param componentList - A string of components to add seperated by a comma `,`
* @sign public this .addComponent(String Component1[, .., String ComponentN])
* @param Component# - Component ID to add.
* Adds a component to the selected entities or entity.
*
* Components are used to extend the functionality of entities.
* This means it will copy properties and assign methods to
* augment the functionality of the entity.
*
* There are multiple methods of adding components. Passing a
* string with a list of component names or passing multiple
* arguments with the component names.
*
* @example
* ~~~
* this.addComponent("2D, Canvas");
* this.addComponent("2D", "Canvas");
* ~~~
*/
addComponent: function (id) {
var uninit = [], c = 0, ul, //array of components to init
i = 0, l, comps;
//add multiple arguments
if (arguments.length > 1) {
l = arguments.length;
for (; i < l; i++) {
this.__c[arguments[i]] = true;
uninit.push(arguments[i]);
}
//split components if contains comma
} else if (id.indexOf(',') !== -1) {
comps = id.split(rlist);
l = comps.length;
for (; i < l; i++) {
this.__c[comps[i]] = true;
uninit.push(comps[i]);
}
//single component passed
} else {
this.__c[id] = true;
uninit.push(id);
}
//extend the components
ul = uninit.length;
for (; c < ul; c++) {
comp = components[uninit[c]];
this.extend(comp);
//if constructor, call it
if (comp && "init" in comp) {
comp.init.call(this);
}
}
this.trigger("NewComponent", ul);
return this;
},
/**@
* #.requires
* @comp Crafty Core
* @sign public this .requires(String componentList)
* @param componentList - List of components that must be added
* Makes sure the entity has the components listed. If the entity does not
* have the component, it will add it.
* @see .addComponent
*/
requires: function (list) {
var comps = list.split(rlist),
i = 0, l = comps.length,
comp;
//loop over the list of components and add if needed
for (; i < l; ++i) {
comp = comps[i];
if (!this.has(comp)) this.addComponent(comp);
}
return this;
},
/**@
* #.removeComponent
* @comp Crafty Core
* @sign public this .removeComponent(String Component[, soft])
* @param component - Component to remove
* @param soft - Whether to soft remove it (defaults to `true`)
* Removes a component from an entity. A soft remove will only
* refrain `.has()` from returning true. Hard will remove all
* associated properties and methods.
*/
removeComponent: function (id, soft) {
if (soft === false) {
var props = components[id], prop;
for (prop in props) {
delete this[prop];
}
}
delete this.__c[id];
this.trigger("RemoveComponent", id);
return this;
},
/**@
* #.has
* @comp Crafty Core
* @sign public Boolean .has(String component)
* Returns `true` or `false` depending on if the
* entity has the given component.
*
* For better performance, simply use the `.__c` object
* which will be `true` if the entity has the component or
* will not exist (or be `false`).
*/
has: function (id) {
return !!this.__c[id];
},
/**@
* #.attr
* @comp Crafty Core
* @sign public this .attr(String property, * value)
* @param property - Property of the entity to modify
* @param value - Value to set the property to
* @sign public this .attr(Object map)
* @param map - Object where the key is the property to modify and the value as the property value
* @trigger Change - when properties change - {key: value}
* Use this method to set any property of the entity.
* @example
* ~~~
* this.attr({key: "value", prop: 5});
* this.key; //value
* this.prop; //5
*
* this.attr("key", "newvalue");
* this.key; //newvalue
* ~~~
*/
attr: function (key, value) {
if (arguments.length === 1) {
//if just the key, return the value
if (typeof key === "string") {
return this[key];
}
//extend if object
this.extend(key);
this.trigger("Change", key); //trigger change event
return this;
}
//if key value pair
this[key] = value;
var change = {};
change[key] = value;
this.trigger("Change", change); //trigger change event
return this;
},
/**@
* #.toArray
* @comp Crafty Core
* @sign public this .toArray(void)
* This method will simply return the found entities as an array.
*/
toArray: function () {
return slice.call(this, 0);
},
/**@
* #.delay
* @comp Crafty Core
* @sign public this .delay(Function callback, Number delay)
* @param callback - Method to execute after given amount of milliseconds
* @param delay - Amount of milliseconds to execute the method
* The delay method will execute a function after a given amount of time in milliseconds.
*
* Essentially a wrapper for `setTimeout`.
*
* @example
* Destroy itself after 100 milliseconds
* ~~~
* this.delay(function() {
this.destroy();
* }, 100);
* ~~~
*/
delay: function (fn, duration) {
this.each(function () {
var self = this;
setTimeout(function () {
fn.call(self);
}, duration);
});
return this;
},
/**@
* #.bind
* @comp Crafty Core
* @sign public this .bind(String eventName, Function callback)
* @param eventName - Name of the event to bind to
* @param callback - Method to execute when the event is triggered
* Attach the current entity (or entities) to listen for an event.
*
* Callback will be invoked when an event with the event name passed
* is triggered. Depending on the event, some data may be passed
* via an argument to the callback function.
*
* The first argument is the event name (can be anything) whilst the
* second argument is the callback. If the event has data, the
* callback should have an argument.
*
* Events are arbitrary and provide communication between components.
* You can trigger or bind an event even if it doesn't exist yet.
* @example
* ~~~
* this.attr("triggers", 0); //set a trigger count
* this.bind("myevent", function() {
* this.triggers++; //whenever myevent is triggered, increment
* });
* this.bind("EnterFrame", function() {
* this.trigger("myevent"); //trigger myevent on every frame
* });
* ~~~
* @see .trigger, .unbind
*/
bind: function (event, fn) {
//optimization for 1 entity
if (this.length === 1) {
if (!handlers[event]) handlers[event] = {};
var h = handlers[event];
if (!h[this[0]]) h[this[0]] = []; //init handler array for entity
h[this[0]].push(fn); //add current fn
return this;
}
this.each(function () {
//init event collection
if (!handlers[event]) handlers[event] = {};
var h = handlers[event];
if (!h[this[0]]) h[this[0]] = []; //init handler array for entity
h[this[0]].push(fn); //add current fn
});
return this;
},
/**@
* #.unbind
* @comp Crafty Core
* @sign public this .unbind(String eventName[, Function callback])
* @param eventName - Name of the event to unbind
* @param callback - Function to unbind
* Removes binding with an event from current entity.
*
* Passing an event name will remove all events binded to
* that event. Passing a reference to the callback will
* unbind only that callback.
* @see .bind, .trigger
*/
unbind: function (event, fn) {
this.each(function () {
var hdl = handlers[event], i = 0, l, current;
//if no events, cancel
if (hdl && hdl[this[0]]) l = hdl[this[0]].length;
else return this;
//if no function, delete all
if (!fn) {
delete hdl[this[0]];
return this;
}
//look for a match if the function is passed
for (; i < l; i++) {
current = hdl[this[0]];
if (current[i] == fn) {
current.splice(i, 1);
i--;
}
}
});
return this;
},
/**@
* #.trigger
* @comp Crafty Core
* @sign public this .trigger(String eventName[, Object data])
* @param eventName - Event to trigger
* @param data - Arbitrary data that will be passed into every callback as an argument
* Trigger an event with arbitrary data. Will invoke all callbacks with
* the context (value of `this`) of the current entity object.
*
* *Note: This will only execute callbacks within the current entity, no other entity.*
*
* The first argument is the event name to trigger and the optional
* second argument is the arbitrary event data. This can be absolutely anything.
*/
trigger: function (event, data) {
if (this.length === 1) {
//find the handlers assigned to the event and entity
if (handlers[event] && handlers[event][this[0]]) {
var fns = handlers[event][this[0]], i = 0, l = fns.length;
for (; i < l; i++) {
fns[i].call(this, data);
}
}
return this;
}
this.each(function () {
//find the handlers assigned to the event and entity
if (handlers[event] && handlers[event][this[0]]) {
var fns = handlers[event][this[0]], i = 0, l = fns.length;
for (; i < l; i++) {
fns[i].call(this, data);
}
}
});
return this;
},
/**@
* #.each
* @sign public this .each(Function method)
* @param method - Method to call on each iteration
* Iterates over found entities, calling a function for every entity.
*
* The function will be called for every entity and will pass the index
* in the iteration as an argument. The context (value of `this`) of the
* function will be the current entity in the iteration.
* @example
* Destroy every second 2D entity
* ~~~
* Crafty("2D").each(function(i) {
* if(i % 2 === 0) {
* this.destroy();
* }
* });
* ~~~
*/
each: function (fn) {
var i = 0, l = this.length;
for (; i < l; i++) {
//skip if not exists
if (!entities[this[i]]) continue;
fn.call(entities[this[i]], i);
}
return this;
},
/**@
* #.clone
* @comp Crafty Core
* @sign public Entity .clone(void)
* @returns Cloned entity of the current entity
* Method will create another entity with the exact same
* properties, components and methods as the current entity.
*/
clone: function () {
var comps = this.__c,
comp,
prop,
clone = Crafty.e();
for (comp in comps) {
clone.addComponent(comp);
}
for (prop in this) {
if (prop != "0" && prop != "_global" && prop != "_changed" && typeof this[prop] != "function" && typeof this[prop] != "object") {
clone[prop] = this[prop];
}
}
return clone;
},
/**@
* #.setter
* @comp Crafty Core
* @sign public this .setter(String property, Function callback)
* @param property - Property to watch for modification
* @param callback - Method to execute if the property is modified
* Will watch a property waiting for modification and will then invoke the
* given callback when attempting to modify.
*
* *Note: Support in IE<9 is slightly different. The method will be executed
* after the property has been set*
*/
setter: function (prop, fn) {
if (Crafty.support.setter) {
this.__defineSetter__(prop, fn);
} else if (Crafty.support.defineProperty) {
Object.defineProperty(this, prop, {
set: fn,
configurable: true
});
} else {
noSetter.push({
prop: prop,
obj: this,
fn: fn
});
}
return this;
},
/**@
* #.destroy
* @comp Crafty Core
* @sign public this .destroy(void)
* Will remove all event listeners and delete all properties as well as removing from the stage
*/
destroy: function () {
//remove all event handlers, delete from entities
this.each(function () {
this.trigger("Remove");
for (var e in handlers) {
this.unbind(e);
}
delete entities[this[0]];
});
}
};
//give the init instances the Crafty prototype
Crafty.fn.init.prototype = Crafty.fn;
/**
* Extension method to extend the namespace and
* selector instances
*/
Crafty.extend = Crafty.fn.extend = function (obj) {
var target = this, key;
//don't bother with nulls
if (!obj) return target;
for (key in obj) {
if (target === obj[key]) continue; //handle circular reference
target[key] = obj[key];
}
return target;
};
/**@
* #Crafty.extend
* @category Core
* Used to extend the Crafty namespace.
*/
Crafty.extend({
/**@
* #Crafty.init
* @category Core
* @trigger EnterFrame - on each frame - { frame: Number }
* @trigger Load - Just after the viewport is initialised. Before the EnterFrame loops is started
* @sign public this Crafty.init([Number width, Number height])
* @param width - Width of the stage
* @param height - Height of the stage
* Starts the `EnterFrame` interval. This will call the `EnterFrame` event for every frame.
*
* Can pass width and height values for the stage otherwise will default to window size (see `Crafty.DOM.window`).
*
* All `Load` events will be executed.
*
* Uses `requestAnimationFrame` to sync the drawing with the browser but will default to `setInterval` if the browser does not support it.
* @see Crafty.stop
*/
init: function (w, h) {
Crafty.viewport.init(w, h);
//call all arbitrary functions attached to onload
this.trigger("Load");
this.timer.init();
return this;
},
/**@
* #Crafty.stop
* @category Core
* @trigger CraftyStop - when the game is stopped
* @sign public this Crafty.stop(void)
* Stops the EnterFrame interval and removes the stage element.
*
* To restart, use `Crafty.init()`.
* @see Crafty.init
*/
stop: function () {
this.timer.stop();
Crafty.stage.elem.parentNode.removeChild(Crafty.stage.elem);
return this;
},
/**@
* #Crafty.pause
* @category Core
* @trigger Pause - when the game is paused
* @trigger Unpause - when the game is unpaused
* @sign public this Crafty.pause(void)
* Pauses the game by stoping the EnterFrame event from firing. If the game is already paused it is unpaused.
* You can pass a boolean parameter if you want to pause or unpause mo matter what the current state is.
* Modern browsers pauses the game when the page is not visible to the user. If you want the Pause event
* to be triggered when that happens you can enable autoPause in `Crafty.settings`.
* @example
* Have an entity pause the game when it is clicked.
* ~~~
* button.bind("click", function() {
* Crafty.pause();
* });
* ~~~
*/
pause: function (toggle) {
if (arguments.length == 1 ? toggle : !this._paused) {
this.trigger('Pause');
this._paused = true;
Crafty.timer.stop();
Crafty.keydown = {};
} else {
this.trigger('Unpause');
this._paused = false;
Crafty.timer.init();
}
return this;
},
/**@
* #Crafty.timer
* @category Internal
* Handles game ticks
*/
timer: {
prev: (+new Date),
current: (+new Date),
curTime: Date.now(),
init: function () {
var onFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
null;
if (onFrame) {
tick = function () {
Crafty.timer.step();
tickID = onFrame(tick);
}
tick();
} else {
tick = setInterval(Crafty.timer.step, 1000 / FPS);
}
},
stop: function () {
Crafty.trigger("CraftyStop");
if (typeof tick === "number") clearInterval(tick);
var onFrame = window.cancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
null;
if (onFrame) onFrame(tickID);
tick = null;
},
/**@
* #Crafty.timer.step
* @comp Crafty.timer
* @sign public void Crafty.timer.step()
* Advances the game by triggering `EnterFrame` and calls `Crafty.DrawManager.draw` to update the stage.
*/
step: function () {
loops = 0;
this.curTime = Date.now();
if (this.curTime - nextGameTick > 60 * skipTicks) {
nextGameTick = this.curTime - skipTicks;
}
while (this.curTime > nextGameTick) {
Crafty.trigger("EnterFrame", { frame: frame++ });
nextGameTick += skipTicks;
loops++;
}
if (loops) {
Crafty.DrawManager.draw();
}
},
/**@
* #Crafty.timer.getFPS
* @comp Crafty.timer
* @sign public void Crafty.timer.getFPS()
* Returns the target frames per second. This is not an actual frame rate.
*/
getFPS: function () {
return FPS;
},
/**@
* #Crafty.timer.simulateFrames
* @comp Crafty.timer
* Advances the game state by a number of frames and draws the resulting stage at the end. Useful for tests and debugging.
* @sign public this Crafty.timer.simulateFrames(Number frames)
* @param frames - number of frames to simulate
*/
simulateFrames: function (frames) {
while (frames-- > 0) {
Crafty.trigger("EnterFrame", { frame: frame++ });
}
Crafty.DrawManager.draw();
}
},
/**@
* #Crafty.e
* @category Core
* @trigger NewEntity - When the entity is created and all components are added - { id:Number }
* @sign public Entity Crafty.e(String componentList)
* @param componentList - List of components to assign to new entity
* @sign public Entity Crafty.e(String component1[, .., String componentN])
* @param component# - Component to add
* Creates an entity. Any arguments will be applied in the same
* way `.addComponent()` is applied as a quick way to add components.
*
* Any component added will augment the functionality of
* the created entity by assigning the properties and methods from the component to the entity.
* ~~~
* var myEntity = Crafty.e("2D, DOM, Color");
* ~~~
* @see Crafty.c
*/
e: function () {
var id = UID(), craft;
entities[id] = null; //register the space
entities[id] = craft = Crafty(id);
if (arguments.length > 0) {
craft.addComponent.apply(craft, arguments);
}
craft.addComponent("obj"); //every entity automatically assumes obj
Crafty.trigger("NewEntity", { id: id });
return craft;
},
/**@
* #Crafty.c
* @category Core
* @sign public void Crafty.c(String name, Object component)
* @param name - Name of the component
* @param 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 `init` will 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 data is needed before executing.
*
* ~~~
* 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...");
* ~~~
* @see Crafty.e
*/
c: function (id, fn) {
components[id] = fn;
},
/**@
* #Crafty.trigger
* @category Core, Events
* @sign public void Crafty.trigger(String eventName, * data)
* @param eventName - Name of the event to trigger
* @param data - Arbitrary data to pass into the callback as an argument
* This method will trigger every single callback attached to the event name. This means
* every global event and every entity that has a callback.
* @see Crafty.bind
*/
trigger: function (event, data) {
var hdl = handlers[event], h, i, l;
//loop over every object bound
for (h in hdl) {
if (!hdl.hasOwnProperty(h)) continue;
//loop over every handler within object
for (i = 0, l = hdl[h].length; i < l; i++) {
if (hdl[h] && hdl[h][i]) {
//if an entity, call with that context
if (entities[h]) {
hdl[h][i].call(Crafty(+h), data);
} else { //else call with Crafty context
hdl[h][i].call(Crafty, data);
}
}
}
}
},
/**@
* #Crafty.bind
* @category Core, Events
* @sign public Number bind(String eventName, Function callback)
* @param eventName - Name of the event to bind to
* @param callback - Method to execute upon event triggered
* @returns ID of the current callback used to unbind
* Binds to a global event. Method will be executed when `Crafty.trigger` is used
* with the event name.
* @see Crafty.trigger, Crafty.unbind
*/
bind: function (event, callback) {
if (!handlers[event]) handlers[event] = {};
var hdl = handlers[event];
if (!hdl.global) hdl.global = [];
return hdl.global.push(callback) - 1;
},
/**@
* #Crafty.unbind
* @category Core, Events
* @sign public Boolean Crafty.unbind(String eventName, Function callback)
* @param eventName - Name of the event to unbind
* @param callback - Function to unbind
* @sign public Boolean Crafty.unbind(String eventName, Number callbackID)
* @param callbackID - ID of the callback
* @returns True or false depending on if a callback was unbound
* Unbind any event from any entity or global event.
*/
unbind: function (event, callback) {
var hdl = handlers[event], h, i, l;
//loop over every object bound
for (h in hdl) {
if (!hdl.hasOwnProperty(h)) continue;
//if passed the ID
if (typeof callback === "number") {
delete hdl[h][callback];
return true;
}
//loop over every handler within object
for (i = 0, l = hdl[h].length; i < l; i++) {
if (hdl[h][i] === callback) {
delete hdl[h][i];
return true;
}
}
}
return false;
},
/**@
* #Crafty.frame
* @category Core
* @sign public Number Crafty.frame(void)
* Returns the current frame number
*/
frame: function () {
return frame;
},
components: function () {
return components;
},
isComp: function (comp) {
return comp in components;
},
debug: function () {
return entities;
},
/**@
* #Crafty.settings
* @category Core
* Modify the inner workings of Crafty through the settings.
*/
settings: (function () {
var states = {},
callbacks = {};
return {
/**@
* #Crafty.settings.register
* @comp Crafty.settings
* @sign public void Crafty.settings.register(String settingName, Function callback)
* @param settingName - Name of the setting
* @param callback - Function to execute when use modifies setting
* Use this to register custom settings. Callback will be executed when `Crafty.settings.modify` is used.
* @see Crafty.settings.modify
*/
register: function (setting, callback) {
callbacks[setting] = callback;
},
/**@
* #Crafty.settings.modify
* @comp Crafty.settings
* @sign public void Crafty.settings.modify(String settingName, * value)
* @param settingName - Name of the setting
* @param value - Value to set the setting to
* Modify settings through this method.
* @see Crafty.settings.register, Crafty.settings.get
*/
modify: function (setting, value) {
if (!callbacks[setting]) return;
callbacks[setting].call(states[setting], value);
states[setting] = value;
},
/**@
* #Crafty.settings.get
* @comp Crafty.settings