Using a Proxy for $store item #4391
-
I have an object (defined by another library) with numerical properties that I'd like to directly manipulate through Alpine components. When a property on the object changes I'd like to be able to call a function in a different JS library. I thought the best way of doing this would be to Proxy the object and call the function in the handler.set() method, for example: let external_library_object = { value_a: 3, value_b: 707 };
Alpine.store('proxied_object', new Proxy(external_library_object , {
set(obj, prop, val) {
obj[prop] = val;
//Hey something has changed!
call_the_3rd_party_js_library_function();
return true;
},
})); <input type="number" x-data="{value: $store.proxied_object.value_a}" x-model="value">
<input type="number" x-data="{value: $store.proxied_object.value_b}" x-model="value"> However this generates the following errors: Uncaught ReferenceError: value is not defined It looks like a proxied store object is not supported, what's the best way of doing this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Your proxy doesn't have a get trap so you can't read the internal properties right? That being said, I'm not completely sure if the reactivity would work with nested proxies (Alpine already use them). |
Beta Was this translation helpful? Give feedback.
-
The issue is you're not properly using You don't need to do this though the store is automatically reactive, so just create an Alpine.effect that calls the function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set |
Beta Was this translation helpful? Give feedback.
The issue is you're not properly using
Reflect
to pass the same this context.You don't need to do this though
the store is automatically reactive, so just create an Alpine.effect that calls the function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set