You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A trait is a specific block of data. They are added to entities to build up its overall data signature. If you are familiar with ECS, it is our version of a component. It is called a trait instead to not get confused with React or web components.
582
+
Traits are self-contained slices of data you attach to an entity to define its state. They serve the same purpose as components in a traditional ECS. We call them traits to avoid confusion with React or web components.
554
583
555
584
A trait can be created with a schema that describes the kind of data it will hold.
556
585
557
586
```js
558
587
constPosition=trait({ x:0, y:0, z:0 })
559
588
```
560
589
561
-
In cases where the data needs to be initialized for each instance of the trait created, a callback can be passed in to be used a as a lazy initializer.
590
+
A schema supports primitive values with **no** nested objects or arrays. In cases where the data needs to initialized for each instance of the trait, or complex structures are required, a callback initializer can be used.
562
591
563
592
```js
564
-
// ❌ The items array will be shared between every instance of this trait
593
+
// ❌ Arrays and objects are not allowed in trait schemas
565
594
constInventory=trait({
566
595
items: [],
596
+
vec3: { x:0, y:0, z:0}
567
597
max:10,
568
598
})
569
599
570
-
// ✅ With a lazy initializer, each instance will now get its own array
600
+
// ✅ Use a callback initializer for arrays and objects
571
601
constInventory=trait({
572
602
items: () => [],
603
+
vec3: () => ({ x:0, y:0, z:0})
573
604
max:10,
574
605
})
575
606
```
576
607
608
+
> ℹ️ **Why not support nested schemas?**<br>
609
+
> It looks obvious to support nested stores, but doing so makes algorithms that work with the data exponentially more complex. If all data can be assumed scalar then any operation is guaranteed to be the simplest and fastest algorithm possible. This is called the First Normal Form in relational database theory. [You can read more here](https://www.dataorienteddesign.com/dodbook/node3.html#SECTION00340000000000000000).
610
+
577
611
Sometimes a trait only has one field that points to an object instance. In cases like this, it is useful to skip the schema and use a callback directly in the trait.
0 commit comments