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.
583
583
584
584
A trait can be created with a schema that describes the kind of data it will hold.
585
585
586
586
```js
587
587
constPosition=trait({ x:0, y:0, z:0 })
588
588
```
589
589
590
-
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.
591
591
592
592
```js
593
-
// ❌ The items array will be shared between every instance of this trait
593
+
// ❌ Arrays and objects are not allowed in trait schemas
594
594
constInventory=trait({
595
595
items: [],
596
+
vec3: { x:0, y:0, z:0}
596
597
max:10,
597
598
})
598
599
599
-
// ✅ With a lazy initializer, each instance will now get its own array
600
+
// ✅ Use a callback initializer for arrays and objects
600
601
constInventory=trait({
601
602
items: () => [],
603
+
vec3: () => ({ x:0, y:0, z:0})
602
604
max:10,
603
605
})
604
606
```
605
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
+
606
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