hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.74k stars 427 forks source link

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

Closed christophehenry closed 1 year ago

christophehenry commented 1 year ago

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.

lb- commented 1 year ago

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.

lb- commented 1 year ago

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.

christophehenry commented 1 year ago

Ok, thank you. Closing this, then.