How to make an Array subclass observable? #3859
Replies: 1 comment 1 reply
-
Subclassing wont be supported. You might create a wrapper class that
manages the observable array internally instead, or a set of static
utilities to express the same behaviors.
…On Thu, 18 Apr 2024, 22:08 Mateen Kasim, ***@***.***> wrote:
This is essentially a re-ask of #456
<#456>, so I'm wondering if there's
any change 8 years later. I'll use a toy example for an array subclass:
class SpecialArray extends Array<any> {
getNumbersCallCount: number;
constructor(...args: any[]) {
super(...args);
this.getNumbersCallCount = 0;
}
// Returns the subset of values that are numbers, and increments a counter
getNumbers(): SpecialArray {
this.getNumbersCallCount++;
return SpecialArray(...this.filter(v => typeof v === 'number'));
}}
If I include a SpecialArray instance as a value in another observable, it
reverts back to a regular array:
class MyStore {
list: SpecialArray;
constructor() {
list = new SpecialArray(1,2,3,"a","b","c",null);
makeObservable(this, {
list: observable
});
}}
// ... later, in an observerconst store = new MyStore();console.log(store.list.getNumbers()); // Uncaught TypeError: store.list.getNumbers is not a function
I understand the docs <https://mobx.js.org/api.html#observablearray> say
that observable.array "creates a new observable array based on the
provided initialValues," which is probably how the new SpecialArray
properties get stripped off. I can use observable.ref to keep it as a
SpecialArray, but then it just tracks the reference and no longer behaves
as a nice observable.array.
How can I get around this so that store.list acts as both an
observable.array and a SpecialArray?
—
Reply to this email directly, view it on GitHub
<#3859>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAN4NBGG3FJ7XZAOSLN2SRDY6AR2ZAVCNFSM6AAAAABGN6I422VHI2DSMVQWIX3LMV43ERDJONRXK43TNFXW4OZWGUZDKNRZGE>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
mateenkasim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This is essentially a re-ask of #456, so I'm wondering if there's any change 8 years later. I'll use a toy example for an array subclass:
If I include a
SpecialArray
instance as a value in another observable, it reverts back to a regular array:I understand the docs say that
observable.array
"creates a new observable array based on the provided initialValues," which is probably how the newSpecialArray
properties get stripped off. I can useobservable.ref
to keep it as aSpecialArray
, but then it just tracks the reference and no longer behaves as a niceobservable.array
.How can I get around this so that
store.list
acts as both anobservable.array
and aSpecialArray
?Beta Was this translation helpful? Give feedback.
All reactions