hotwired / stimulus

A modest JavaScript framework for the HTML you already have

Home Page:https://stimulus.hotwired.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Array and object methods don't trigger `xValueChanged` methods

christophehenry opened this issue · comments

Take this example:

class TestController extends Stimulus.Controller {
    connect () {
        this.strValue = "Test";
        this.arrValue.push("Test");
        this.objValue["Test"] = "Test";
    }

    strValueChanged(val) {
        console.log(val);
    }

    arrValueChanged(val) {
        console.log(val);
    }

    objValueChanged(val) {
        console.log(val);
    }

    static values = {
        str: {type: String, default: ""},
        arr: {type: Array, default: []},
        obj: {type: Object, default: {}}
    }
}

This will print:

<empty string>
Array []
Object {  }
Test

First and last prints correspond to init and connect() but the two in-between only correspond to the initialization only. This could be solved by using JS' Proxy.

The first three calls to console are the changed callbacks for the initial values. The third is when you change the string value to test in the connect callback.

Pushing to an array value and adding a property to an object value won't work as expected.

As per the other ticket, value properties are getters and setters, not instance values.

https://stimulus.hotwired.dev/reference/values#change-callbacks

Stimulus invokes each change callback after the controller is initialized and again any time its associated data attribute changes. This includes changes as a result of assignment to the value’s setter.

Ok, thank you. Closing this, then.