SvelteJs: Deep observe on computed properties

Viewed 1007

As of now we can do the below using computed properties.

isTypeRange: ({ field }) => {
        return field && field.type === "Range";
      }

Can we do something anything like this?

fieldLength: ({field.values.length}) => {
  return field.values.length;
}

Following this link https://github.com/sveltejs/svelte/issues/11 eventually led me to https://github.com/sveltejs/svelte-extras/. But that again explains deep observe.

Update: P.S. I know {field.values.length} is invalid javascript, I am just trying to show what I want to achieve. Meaning observing nested properties similar to how ember does

fieldLength: Ember.computed('field.values.[]', {
get(){}, set(){}
})
1 Answers

The short answer is no — in Svelte, changes are tracked at the top level (of a component, or of a store), as monitoring nested properties separately would involve a lot more code and internal book-keeping. So fieldLength will be recalculated whenever field changes (where a 'change' can mean either a new object, or a mutation of the existing one unless you're using the immutable option). Nothing that depends on fieldLength will be updated unless the length has changed, however.

The longer answer is that ({field.values.length}) => ... is invalid JavaScript, but there is a valid (if sightly confusing-looking) way to express the same idea:

fieldLength: ({field:{values:{length}}}) => length

It's possible that future versions of Svelte could track nested properties and only recompute values when they change — if so, it would figure out which nested properties were dependencies by using that destructuring syntax. But regardless of our future intentions that's an approach that will work today, albeit with the occasional unnecessary recomputation.

Related