ractivejs / ractive

Next-generation DOM manipulation
http://ractive.js.org
MIT License
5.94k stars 396 forks source link

Using decorators inside 'observe' propriety #3258

Closed ericgruby01 closed 6 years ago

ericgruby01 commented 6 years ago

Description:

Hi,

When I try to execute:

  observe: {
    name(newName) {
        if (newName === 'Eric') {
        this.nodes['inputName'].style.color = 'skyblue'
      } else {
        // if the line below is uncommented, the code stop working.
        this.nodes['inputName'].style.color = 'tomato';
      }
    }
  }

I get:

Uncaught TypeError: Cannot read property 'inputName' of undefined

On my template, the decorator seems fine:

<input as-tracked="'inputName'" value="{{name}}">

I believe it has something to do with Ractive lifecycle. I'm pretty sure I've missed something on the documentation...

Versions affected:

I'm using 1.0.0-build-99

Platforms affected:

Whatever platform I tried.

Reproduction:

evs-chris commented 6 years ago

The issue here is that the observer is running before the instance is rendered, which means that no nodes will exist yet. If you skip init with the observer, it won't fire until the next change, which in this case, won't be until everything's rendered. The safest approach is to guard the observer callback against the target node not being present. You can add nodes: {} to your instance init options to avoid having to make sure that part is present.

An even safer approach for this case would be to use an inline style directive.

ericgruby01 commented 6 years ago

😅 It was a lifecycle thing after all... Thanks for The Quick response.