admin管理员组文章数量:1356824
In mobx if I want to use interheritance I need to use makeObservable rather than makeAutoObservable. But using makeObservable requires I name the actions that mutate state so how can I declare a setter to be an action given it has the same name as the getter?
In other words what goes where I wrote SETTER_FOR_MYVAR or what is another way to achieve the same effect?
class BaseClass {
_myvar = null
set myvar(val) {
this._myvar = val;
}
get myvar() {
return this._myvar;
}
other_action() {
this._myvar = 5;
}
constructor() {
makeObservable(this, {
_myvar: observable,
other_action: action,
SETTER_FOR_MYVAR: action
});
}
}
Yes, I know I could farm it out to yet another helper function _myvar_setter and declare that an action but that seems ugly and I'm hoping there is a better way.
In mobx if I want to use interheritance I need to use makeObservable rather than makeAutoObservable. But using makeObservable requires I name the actions that mutate state so how can I declare a setter to be an action given it has the same name as the getter?
In other words what goes where I wrote SETTER_FOR_MYVAR or what is another way to achieve the same effect?
class BaseClass {
_myvar = null
set myvar(val) {
this._myvar = val;
}
get myvar() {
return this._myvar;
}
other_action() {
this._myvar = 5;
}
constructor() {
makeObservable(this, {
_myvar: observable,
other_action: action,
SETTER_FOR_MYVAR: action
});
}
}
Yes, I know I could farm it out to yet another helper function _myvar_setter and declare that an action but that seems ugly and I'm hoping there is a better way.
Share Improve this question asked Jun 21, 2021 at 0:11 Peter GerdesPeter Gerdes 3,0261 gold badge28 silver badges33 bronze badges1 Answer
Reset to default 8Just mark myvar
as puted
, everything should work out of the box (If I understand correctly what you want):
constructor() {
makeObservable(this, {
_myvar: observable,
myvar: puted,
other_action: action
});
}
Codesandbox
Excerpt from the docs:
It is possible to define a setter for puted values as well. Note that these setters cannot be used to alter the value of the puted property directly, but they can be used as an "inverse" of the derivation. Setters are automatically marked as actions.
Example:
class Dimension {
length = 2
constructor() {
makeAutoObservable(this)
}
get squared() {
return this.length * this.length
}
set squared(value) {
this.length = Math.sqrt(value)
}
}
More info in the docs
本文标签: javascriptMake setter an action using Mobx makeObservable in presence of getterStack Overflow
版权声明:本文标题:javascript - Make setter an action using Mobx makeObservable in presence of getter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744071141a2585905.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论