I know you're trying to comply with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe
But I don't see how it's useful in any way to exclude it.
I'm not familiar enough with TS or the library to do a pull, but I think it'd involve modifying spliceWithArray so it has something like this at https://github.com/mobxjs/mobx/blob/master/src/types/observablearray.ts#L82
const oldValue = adm.array.slice()
and then in the parameters and emit of notifyArraySplice you'd add the oldValue.
The main reason it is not included in the splice info (I guess), is that the splice is now currently build up using data you need to know anyway to perform a splice (removedItems is returned from the splice operation). Putting the oldValues in the splice info would require calculating additional information to just emit this event. This event might be emitted very often, so the smaller / simpler the event data is, the better.
But note that you can recompute the old collection simply from the splice: const oldValue = splice.object.slice().splice(splice.index, splice.addedCount, ...splice.removed)
Ah ok good to know.
That being said, I will added the fields added and addedCount. Which is cheap and useful for debugging purposes :)
@mweststrate You said that it's extra overhead to include the oldValue on splice changes and I agree. This makes me wonder why include the object option?
You can only use observe if the MobX observable being observed is already in scope, and if that's the case won't object be already equal to the observable already in scope?
const x = observable([])
observe(x, function(change) {
// change.object and x will always be equal here right?
})
Or am I mistaken, and they can somehow get out of sync?
@AriaFallah object is just a pointer, not a copy. And it is very useful if you attach the same observer function to multiple observables, to find out which one fired.
And it is very useful if you attach the same observer function to multiple observables, to find out which one fired.
How do you do this? I don't think I've seen it in the docs.
Ehh.. just reuse the function :) Saves some unnecessary closures.
function onSplice(splice) {
// splice.object is now either a1 or a2
// do something
}
const d1 = ar1.observe(onSplice)
const d2 = ar2.observe(onSplice)
@mweststrate I thought you needed to
import { observe } from 'mobx'
Is it actually part of the prototype?
Yep (except for objects to avoid name collisions). But the idiomatic is indeed:
const d1 = observe(ar1, onSplice)
const d2 = observe(ar2, onSplice)
But the same principle applies