forked from craftyjs/Crafty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.js
1765 lines (1604 loc) · 60.4 KB
/
core.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
var version = require('./version');
/**@
* #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.
*
* If there is more than one match, the return value is an Array-like object listing the ID numbers of each matching entity. If there is exactly one match, the entity itself is returned. If you're not sure how many matches to expect, check the number of matches via Crafty(...).length. Alternatively, use Crafty(...).each(...), which works in all cases.
*
* @example
* ~~~
* Crafty("MyComponent")
* Crafty("Hello 2D Component")
* Crafty("Hello, 2D, Component")
* ~~~
*
* The first selector will return all entities that have the component `MyComponent`. The second will return all entities that have `Hello` and `2D` and `Component` whereas the last will return all entities that have at least one of those components (or).
*
* ~~~
* Crafty("*")
* ~~~
* Passing `*` will select all entities.
*
* ~~~
* Crafty(1)
* ~~~
* Passing an integer will select the entity with that `ID`.
*
* To work directly with an array of entities, use the `get()` method on a selection.
* To call a function in the context of each entity, use the `.each()` method.
*
* The event related methods such as `bind` and `trigger` will work on selections of entities.
*
* @see .get
* @see .each
*/
var Crafty = function (selector) {
return new Crafty.fn.init(selector);
},
// Internal variables
GUID, frame, components, entities, handlers, onloads,
slice, rlist, rspace, milliSecPerFrame;
initState = function () {
GUID = 1; //GUID for entity IDs
frame = 0;
components = {}; //map of components and their functions
entities = {}; //map of entities and their data
handlers = {}; //global event handlers
onloads = []; //temporary storage of onload handlers
slice = Array.prototype.slice;
rlist = /\s*,\s*/;
rspace = /\s+/;
};
initState();
/**@
* #Crafty Core
* @category Core
* @trigger NewEntityName - After setting new name for entity - String - entity name
* @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 === '*') {
i = 0;
for (e in entities) {
// entities is something like {2:entity2, 3:entity3, 11:entity11, ...}
// The for...in loop sets e to "2", "3", "11", ... i.e. all
// the entity ID numbers. e is a string, so +e converts to number type.
this[i] = +e;
i++;
}
this.length = i;
// if there's only one entity, return the actual entity
if (i === 1) {
return entities[this[0]];
}
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)
// if there's only one entity, return the actual entity
if (elem === 1) {
return entities[this[elem - 1]];
}
} 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;
},
/**@
* #.setName
* @comp Crafty Core
* @sign public this .setName(String name)
* @param name - A human readable name for debugging purposes.
*
* @example
* ~~~
* this.setName("Player");
* ~~~
*/
setName: function (name) {
var entityName = String(name);
this._entityName = entityName;
this.trigger("NewEntityName", entityName);
return this;
},
/**@
* #.addComponent
* @comp Crafty Core
* @sign public this .addComponent(String componentList)
* @param componentList - A string of components to add separated 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.
*
* For adding multiple components, you can either pass a string with
* all the component names (separated by commas), or pass each component name as
* an argument.
*
* If the component has a function named `init` it will be called.
*
* If the entity already has the component, the component is skipped (nothing happens).
*
* @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, comp;
//add multiple arguments
if (arguments.length > 1) {
l = arguments.length;
for (; i < l; i++) {
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++) {
uninit.push(comps[i]);
}
//single component passed
} else {
uninit.push(id);
}
//extend the components
ul = uninit.length;
for (; c < ul; c++) {
if (this.__c[uninit[c]] === true)
continue;
this.__c[uninit[c]] = true;
comp = components[uninit[c]];
this.extend(comp);
//if constructor, call it
if (comp && "init" in comp) {
comp.init.call(this);
}
}
this.trigger("NewComponent", uninit);
return this;
},
/**@
* #.toggleComponent
* @comp Crafty Core
* @sign public this .toggleComponent(String ComponentList)
* @param ComponentList - A string of components to add or remove separated by a comma `,`
* @sign public this .toggleComponent(String Component1[, .., String componentN])
* @param Component# - Component ID to add or remove.
* Add or Remove Components from an entity.
*
* @example
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.toggleComponent("Test,Test2"); //Remove Test, add Test2
* e.toggleComponent("Test,Test2"); //Add Test, remove Test2
* ~~~
*
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.toggleComponent("Test","Test2"); //Remove Test, add Test2
* e.toggleComponent("Test","Test2"); //Add Test, remove Test2
* e.toggleComponent("Test"); //Remove Test
* ~~~
*/
toggleComponent: function (toggle) {
var i = 0,
l, comps;
if (arguments.length > 1) {
l = arguments.length;
for (; i < l; i++) {
if (this.has(arguments[i])) {
this.removeComponent(arguments[i]);
} else {
this.addComponent(arguments[i]);
}
}
//split components if contains comma
} else if (toggle.indexOf(',') !== -1) {
comps = toggle.split(rlist);
l = comps.length;
for (; i < l; i++) {
if (this.has(comps[i])) {
this.removeComponent(comps[i]);
} else {
this.addComponent(comps[i]);
}
}
//single component passed
} else {
if (this.has(toggle)) {
this.removeComponent(toggle);
} else {
this.addComponent(toggle);
}
}
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.
*
* (In the current version of Crafty, this function behaves exactly the same
* as `addComponent`. By convention, developers have used `requires` for
* component dependencies -- i.e. to indicate specifically that one component
* will only work properly if another component is present -- and used
* `addComponent` in all other situations.)
*
* @see .addComponent
*/
requires: function (list) {
return this.addComponent(list);
},
/**@
* #.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 (the default) will only
* refrain `.has()` from returning true. Hard will remove all
* associated properties and methods.
*
* @example
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.removeComponent("Test"); //Soft remove Test component
* e.removeComponent("Test", false); //Hard remove Test component
* ~~~
*/
removeComponent: function (id, soft) {
var comp = components[id];
this.trigger("RemoveComponent", id);
if (comp && "remove" in comp) {
comp.remove.call(this, false);
}
if (soft === false && comp) {
for (var prop in comp) {
delete this[prop];
}
}
delete this.__c[id];
return this;
},
/**@
* #.getId
* @comp Crafty Core
* @sign public Number .getId(void)
* Returns the ID of this entity.
*
* For better performance, simply use the this[0] property.
*
* @example
* Finding out the `ID` of an entity can be done by returning the property `0`.
* ~~~
* var ent = Crafty.e("2D");
* ent[0]; //ID
* ent.getId(); //also ID
* ~~~
*/
getId: function () {
return this[0];
},
/**@
* #.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
* @trigger Change - when properties change - {key: value}
*
* @sign public this .attr(String property, Any value[, Boolean silent[, Boolean recursive]])
* @param property - Property of the entity to modify
* @param value - Value to set the property to
* @param silent - If you would like to supress events
* @param recursive - If you would like merge recursively
* Use this method to set any property of the entity.
*
* @sign public this .attr(Object map[, Boolean silent[, Boolean recursive]])
* @param map - Object where each key is the property to modify and the value as the property value
* @param silent - If you would like to supress events
* @param recursive - If you would like merge recursively
* Use this method to set multiple properties of the entity.
*
* Setter options:
* `silent`: If you want to prevent it from firing events.
* `recursive`: If you pass in an object you could overwrite sibling keys, this recursively merges instead of just merging it. This is `false` by default, unless you are using dot notation `name.first`.
*
* @sign public Any .attr(String property)
* @param property - Property of the entity to modify
* @returns Value - the value of the property
* Use this method to get any property of the entity. You can also retrieve the property using `this.property`.
*
*
* @example
* ~~~
* this.attr({key: "value", prop: 5});
* this.attr("key"); // returns "value"
* this.attr("prop"); // returns 5
* this.key; // "value"
* this.prop; // 5
*
* this.attr("key", "newvalue");
* this.attr("key"); // returns "newvalue"
* this.key; // "newvalue"
*
* this.attr("parent.child", "newvalue");
* this.parent; // {child: "newvalue"};
* this.attr('parent.child'); // "newvalue"
* ~~~
*/
attr: function (key, value, silent, recursive) {
if (arguments.length === 1 && typeof arguments[0] === 'string') {
return this._attr_get(key);
} else {
return this._attr_set(key, value, silent, recursive);
}
},
/**
* Internal getter method for data on the entity. Called by `.attr`.
*
* example
* ~~~
* person._attr_get('name'); // Foxxy
* person._attr_get('contact'); // {email: 'fox_at_example.com'}
* person._attr_get('contact.email'); // fox_at_example.com
* ~~~
*/
_attr_get: function(key, context) {
var first, keys, subkey;
if (typeof context === "undefined" || context === null) {
context = this;
}
if (key.indexOf('.') > -1) {
keys = key.split('.');
first = keys.shift();
subkey = keys.join('.');
return this._attr_get(keys.join('.'), context[first]);
} else {
return context[key];
}
},
/**
* Internal setter method for attributes on the component. Called by `.attr`.
*
* Options:
*
* `silent`: If you want to prevent it from firing events.
*
* `recursive`: If you pass in an object you could overwrite
* sibling keys, this recursively merges instead of just
* merging it. This is `false` by default, unless you are
* using dot notation `name.first`.
*
* example
* ~~~
* person._attr_set('name', 'Foxxy', true);
* person._attr_set('name', 'Foxxy');
* person._attr_set({name: 'Foxxy'}, true);
* person._attr_set({name: 'Foxxy'});
* person._attr_set('name.first', 'Foxxy');
* ~~~
*/
_attr_set: function() {
var data, silent, recursive;
if (typeof arguments[0] === 'string') {
data = this._set_create_object(arguments[0], arguments[1]);
silent = !!arguments[2];
recursive = arguments[3] || arguments[0].indexOf('.') > -1;
} else {
data = arguments[0];
silent = !!arguments[1];
recursive = !!arguments[2];
}
if (!silent) {
this.trigger('Change', data);
}
if (recursive) {
this._recursive_extend(data, this);
} else {
this.extend.call(this, data);
}
return this;
},
/**
* If you are setting a key of 'foo.bar' or 'bar', this creates
* the appropriate object for you to recursively merge with the
* current attributes.
*/
_set_create_object: function(key, value) {
var data = {}, keys, first, subkey;
if (key.indexOf('.') > -1) {
keys = key.split('.');
first = keys.shift();
subkey = keys.join('.');
data[first] = this._set_create_object(subkey, value);
} else {
data[key] = value;
}
return data;
},
/**
* Recursively puts `new_data` into `original_data`.
*/
_recursive_extend: function(new_data, original_data) {
var key;
for (key in new_data) {
if (new_data[key].constructor.name === 'Object') {
original_data[key] = this._recursive_extend(new_data[key], original_data[key]);
} else {
original_data[key] = new_data[key];
}
}
return original_data;
},
/**@
* #.toArray
* @comp Crafty Core
* @sign public this .toArray(void)
*
* This method will simply return the found entities as an array of ids. To get an array of the actual entities, use `get()`.
* @see .get
*/
toArray: function () {
return slice.call(this, 0);
},
/**@
* #.timeout
* @comp Crafty Core
* @sign public this .timeout(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.timeout(function() {
this.destroy();
* }, 100);
* ~~~
*/
timeout: function (callback, duration) {
this.each(function () {
var self = this;
setTimeout(function () {
callback.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.
*
* Unlike DOM events, Crafty events are exectued synchronously.
*
* @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, callback) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
//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(callback); //add current callback
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(callback); //add current callback
});
return this;
},
/**@
* #.uniqueBind
* @comp Crafty Core
* @sign public Number .uniqueBind(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
*
* Works like Crafty.bind, but prevents a callback from being bound multiple times.
*
* @see .bind
*/
uniqueBind: function (event, callback) {
this.unbind(event, callback);
this.bind(event, callback);
},
/**@
* #.one
* @comp Crafty Core
* @sign public Number one(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
*
* Works like Crafty.bind, but will be unbound once the event triggers.
*
* @see .bind
*/
one: function (event, callback) {
var self = this;
var oneHandler = function (data) {
callback.call(self, data);
self.unbind(event, oneHandler);
};
return self.bind(event, oneHandler);
},
/**@
* #.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 bound to
* that event. Passing a reference to the callback will
* unbind only that callback.
* @see .bind, .trigger
*/
unbind: function (event, callback) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
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 (!callback) {
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] == callback) {
delete current[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.
*
* Unlike DOM events, Crafty events are exectued synchronously.
*/
trigger: function (event, data) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
if (this.length === 1) {
//find the handlers assigned to the event and entity
if (handlers[event] && handlers[event][this[0]]) {
var callbacks = handlers[event][this[0]],
i;
for (i = 0; i < callbacks.length; i++) {
if (typeof callbacks[i] === "undefined") {
callbacks.splice(i, 1);
i--;
} else {
callbacks[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 callbacks = handlers[event][this[0]],
i;
for (i = 0; i < callbacks.length; i++) {
if (typeof callbacks[i] === "undefined") {
callbacks.splice(i, 1);
i--;
} else {
callbacks[i].call(this, data);
}
}
}
});
return this;
},
/**@
* #.each
* @comp Crafty Core
* @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 (func) {
var i = 0,
l = this.length;
for (; i < l; i++) {
//skip if not exists
if (!entities[this[i]]) continue;
func.call(entities[this[i]], i);
}
return this;
},
/**@
* #.get
* @comp Crafty Core
* @sign public Array .get()
* @returns An array of entities corresponding to the active selector
*
* @sign public Entity .get(Number index)
* @returns an entity belonging to the current selection
* @param index - The index of the entity to return. If negative, counts back from the end of the array.
*
*
* @example
* Get an array containing every "2D" entity
* ~~~
* var arr = Crafty("2D").get()
* ~~~
* Get the first entity matching the selector
* ~~~
* // equivalent to Crafty("2D").get()[0], but doesn't create a new array
* var e = Crafty("2D").get(0)
* ~~~
* Get the last "2D" entity matching the selector
* ~~~
* var e = Crafty("2D").get(-1)
* ~~~
*
*/
get: function(index) {
var l = this.length;
if (typeof index !== "undefined") {
if (index >= l || index+l < 0)
return undefined;
if (index>=0)
return entities[this[index]];
else
return entities[this[index+l]];
} else {
var i=0, result = [];
for (; i < l; i++) {
//skip if not exists
if (!entities[this[i]]) continue;
result.push( entities[this[i]] );
}
return result;
}
},
/**@
* #.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.
*
*/
setter: function (prop, callback) {
if (Crafty.support.setter) {
this.__defineSetter__(prop, callback);
} else if (Crafty.support.defineProperty) {
Object.defineProperty(this, prop, {
set: callback,
configurable: true
});
}
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 () {
var comp;
this.trigger("Remove");
for (var compName in this.__c) {
comp = components[compName];
if (comp && "remove" in comp)
comp.remove.call(this, true);
}
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;
/**@
* #Crafty.extend
* @category Core
* Used to extend the Crafty namespace.
*
*/
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({
/**@
* #Crafty.init
* @category Core
* @trigger Load - Just after the viewport is initialised. Before the EnterFrame loops is started
* @sign public this Crafty.init([Number width, Number height, String stage_elem])
* @sign public this Crafty.init([Number width, Number height, HTMLElement stage_elem])
* @param Number width - Width of the stage
* @param Number height - Height of the stage
* @param String or HTMLElement stage_elem - the element to use for the stage
*
* Sets the element to use as the stage, creating it if necessary. By default a div with id 'cr-stage' is used, but if the 'stage_elem' argument is provided that will be used instead. (see `Crafty.viewport.init`)
*
* 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.