Comment on page
Mixins
Learn how to create and apply mixins
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.
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.events.js
const {Mixin} = require ('@onehilltech/blueprint');
const Events = Mixin.create ({
on (name, method) {
// ...
},
once (name, method) {
// ...
}
emit (name, ...args) {
// ...
}
});
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.
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.const { BO } = require ('@onehilltech/blueprint');
const Events = require ('./events');
const Person = BO.extend (Events, {
// The person class definition
});
Now, anytime we create a
Person
class, it will have access to the methods and data properties defined in the Events
mixin.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.const { BO } = require ('@onehilltech/blueprint');
const Events = require ('./events');
let president = Person.create (Events, {
firstName: 'Barack',
lastName: 'Obama'
});
Now, only the
president
instance will have access to the methods and data properties defined in the Events
mixin.Last modified 5yr ago