types.compose and lifecycle methods #1885
-
Question I'm working on a project using types.compose to combine several models into one. Specifically we have some smaller models we call Traits that we compose into larger ones. For example a trait could be "Noteable" that lets another model, for example a Project, an Employee or a Media-model, get a list of notes attached to it and some methods to load and handle this. (This corresponds to traits in a Laravel back-end). Works great but I have a question about how lifecycle methods are handled when using compose. Take the following example:
To me it seems like BOTH afterCreates are run, but calling testMethod on an instance of project will only run the testMethod from Noteable. Will this always be the case, also for the other lifecycle methods? How would I go about having the testMethod from Project called? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @mortmoe! You could use the approach outlined in the import { types } from "mobx-state-tree";
const Note = types.model("note", {
id: types.identifierNumber,
description: types.string
});
const Noteable = types
.model({
notes: types.optional(types.array(Note), [])
})
.actions((self) => {
const superTestMethod = self.testMethod;
return {
afterCreate() {
console.log("After create in Notable");
},
testMethod() {
if (superTestMethod) superTestMethod();
console.log("Testmethod in Noteable");
}
};
});
const Project = types
.compose(
types
.model({
id: types.identifierNumber
})
.actions((self) => ({
afterCreate() {
console.log("After create in Project");
},
testMethod() {
console.log("Testmethod in Project");
}
})),
Noteable
)
.named("project");
const project = Project.create({ id: 1 });
project.testMethod();
// => After create in Project
// => After create in Notable
// => Testmethod in Project
// => Testmethod in Noteable |
Beta Was this translation helpful? Give feedback.
Hi @mortmoe!
You could use the approach outlined in the
Simulate inheritance by using type composition
part of the documentation and save a reference to the "super"testMethod
and call that manually intestMethod
inNoteable
: