silentmatt / expr-eval

Mathematical expression evaluator in JavaScript
http://silentmatt.com/javascript-expression-evaluator/
MIT License
1.18k stars 239 forks source link

Using expr-eval with vuejs #241

Closed bscbrn closed 3 years ago

bscbrn commented 3 years ago

Hello, I am trying to use expr-eval with vuejs. I have defined an exprEvalContext empty object in the vue data and passed to parser.evaluate function. When the evaluated expression create a new variable in the context this does not trigger vue updates and this is norbal for how vue works. A Vue.set should be done when the parser set any variable. How this could be done?

silentmatt commented 3 years ago

There's not currently a way to do something like that automatically, i.e. we don't have callback hooks or anything to handle assignments. Depending on the browser support you need, you could use a proxy object to accomplish that. Otherwise you would probably need to check for changes to the context object yourself and trigger the updates. Or it's possible someone's written that already. I haven't used Vue myself, so I don't know if something like that exists or not.

bscbrn commented 3 years ago

Thank you. I found out that by calling Vue.set to "initialize" the variables used in the expressions is sufficient to make them reactive. This shall be done before the expression evaluation. Later on, any regular parser evaluation assignment triggers the Vue reaction system.

silentmatt commented 3 years ago

Nice!

bscbrn commented 3 years ago

Based on #244 I suceeded in replacing the assignment operator as follows:

parser.binaryOps['='] = (a, b) => storeRef.commit('writeExprVar', { name: a, val: b })

the 'writeExprVar' is a vue mutation that executes the Vue.set on the named variable. It works very well. Thank you @silentmatt