Mixins
Learn how to create and apply mixins
Overview
A mixin is an entity that captures reusable data properties and methods, but cannot be instantiated. The reason we have mixins is because the our object model uses single inheritance—meaning a class can only have one class as its base class. If we want multiple classes to share data properties and methods from multiple entity types, then it is not possible.
Creating a Mixin
You create a mixin using the Mixin.create()
method. The create method takes a definition hash that contains data properties and methods, which is similar to how you created a class.
Using a Mixin
Once we have created a mixin, you can use it in two ways. The first approach is applying the mixin to the class definition. When you apply a mixin to a class definition, all instances of the class will have the mixin as part of their definition. The second approach is to apply the mixin to an instance when it is created. When we use this approach, only the created instance will have the mixin as part of its definition. It does not impact the other instances of the class.
Applying Mixin to Class Definition
The extend()
method takes optional list of mixins before the class definition.
The signature of the extend()
method isBO.extend ([Mixin1, Mixin2, Mixin3,] definition)
.
For example, let's assume we want to mix in the Events
mixin with the Person
class. We can do that by preceding the definition with the mixin.
Now, anytime we create a Person
class, it will have access to the methods and data properties defined in the Events
mixin.
Applying Mixin to Object Instance
Similar to the extend()
method, the create()
method takes optional list of mixins that before the class definition.
The signature of the create()
method isBO.create ([Mixin1, Mixin2, Mixin3,] definition)
For example, let's assume we want to mix in the Events
mixin with the Person
class. We can do that by preceding the definition with the mixin.
Now, only the president
instance will have access to the methods and data properties defined in the Events
mixin.
Last updated