Replies: 2 comments 5 replies
-
I am not sure if inheritance is a good way of using Mobx. Mobx supports limited inheritance: https://mobx.js.org/subclassing.html Moreover inheritance creates more issues in your case because you won't be able to extend from many objects at the same time (JS doesn't support multiple inheritance). It looks like you need something like Entity-Component-System and this is out of Mobx responsibilty: https://en.wikipedia.org/wiki/Entity_component_system I've found some snippet and it looks like it's going to work with Mobx. Not sure if it's going to help. class Character {
abilities = [];
addAbility (...abilities) {
for (const a of abilities) {
this.abilities.push(a);
}
return this;
}
getAbility (AbilityClass) {
for (const a of this.abilities) {
if (a instanceof AbilityClass) {
return a;
}
}
return null;
}
}
// Abilities
class Ability {}
class HealthAbility extends Ability {
health = 100;
maxHealth = 100;
}
class MovementAbility extends Ability {
x = 0;
y = 0;
moveTo(x, y) {
this.x = x;
this.y = y;
}
}
class SpellCastAbility extends Ability {
mana = 100;
maxMana = 100;
cast () {
this.mana--;
}
}
class MeleeFightAbility extends Ability {
stamina = 100;
maxStamina = 100;
constructor (power) {
this.power = power;
}
hit () {
this.stamina--;
}
}
// characters
class CharactersFactory {
createMage () {
return new Character().addAbility(
new MovementAbility(),
new HealthAbility(),
new SpellCastAbility()
);
}
createWarrior () {
return new Character().addAbility(
new MovementAbility(),
new HealthAbility(),
new MeleeFightAbility(3)
);
}
createPaladin () {
return new Character().addAbility(
new MovementAbility(),
new HealthAbility(),
new SpellCastAbility(),
new MeleeFightAbility(2)
);
}
} |
Beta Was this translation helpful? Give feedback.
-
Constructors in mixins are technically fine (there is always an implicit constructor anyway). The reason why mixin shouldn't have one is the composability/reusability aspect - if each mixin has different constructor signature you can't really "mix" them together. // @ts-ignore
constructor(...args) {
super(...args);
makeObservable(this, {
age: observable,
grow: action,
});
} Not sure if it somehow messes up types. Alternatively, but less conviniently, each mixin can expose unique init method, which you would have to call manually from final constructor. |
Beta Was this translation helpful? Give feedback.
-
For example, using mix-ins to extends multiple utility classes, like this:
The example I provided cannot run correctly because mixin classes cannot have constructors, but I would also like to mark the member methods as observable or action in the mixin classes.
What should I do?
or, What is the common approach within the mobx community for dealing with this problem using other methods?
Beta Was this translation helpful? Give feedback.
All reactions