From b51f4434f1f2c693092d56afe90ee6bddfa690bb Mon Sep 17 00:00:00 2001 From: Aiden Bai Date: Sat, 24 Apr 2021 13:08:44 -0700 Subject: [PATCH] fix: compute function methods not being able to access `this` as state --- .gitignore | 4 ++-- src/core/utils/computeExpression.ts | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 2783fc5..8c7ddad 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ package-lock.json yarn-error.log # Tests -*.html +/*.html coverage # Build source @@ -15,4 +15,4 @@ dist/ .DS_Store # Misc -scratch.md \ No newline at end of file +scratch.md diff --git a/src/core/utils/computeExpression.ts b/src/core/utils/computeExpression.ts index e012ee7..0a5cd2f 100644 --- a/src/core/utils/computeExpression.ts +++ b/src/core/utils/computeExpression.ts @@ -2,18 +2,17 @@ import { UnknownKV } from '../../models/generics'; import { Refs } from '../../models/structs'; import { expressionPropRE } from './patterns'; -export const resolveStateInExpression = (unresolvedExpression: string, deps?: string[]): string => { +export const resolveStateInExpression = ( + unresolvedExpression: string, + deps: string[] = [] +): string => { // This dynamically appends `$state.` to the front of standalone props, allowing the // user to write less and us to compile and run faster without with() {} - if (deps) { - let expression = unresolvedExpression; - deps.forEach((dep) => { - expression = expression.replace(expressionPropRE(dep), `$state.${dep}`); - }); - return expression; - } else { - return `with($state){${unresolvedExpression}}`; - } + let expression = unresolvedExpression; + deps.forEach((dep) => { + if (dep !== expression) expression = expression.replace(expressionPropRE(dep), `$state.${dep}`); + }); + return expression; }; export const computeExpression = ( @@ -31,8 +30,9 @@ export const computeExpression = ( // This "revives" a function from a string, only using the new Function syntax once during compilation. // This is because raw function is ~50,000x faster than new Function const computeFunction = new Function( - `return function(${specialPropertiesNames.join(',')}){${resolvedExpression}}` + `'use strict';return function(${specialPropertiesNames.join(',')}){${resolvedExpression}}` )(); + const emit = (name: string, options?: CustomEventInit, dispatchGlobal = true) => { const event = new CustomEvent(name, options); const target = dispatchGlobal ? window : el || window; @@ -43,7 +43,7 @@ export const computeExpression = ( try { const value = state[expression]; if (value) { - return typeof value === 'function' ? value() : value; + return typeof value === 'function' ? value.bind(state)() : value; } else { return computeFunction(state, el, emit, event, refs); }