Skip to content
This repository has been archived by the owner on May 19, 2023. It is now read-only.

Commit

Permalink
fix: compute function methods not being able to access this as state
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenybai committed Apr 24, 2021
1 parent bdf24f5 commit b51f443
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ package-lock.json
yarn-error.log

# Tests
*.html
/*.html
coverage

# Build source
Expand All @@ -15,4 +15,4 @@ dist/
.DS_Store

# Misc
scratch.md
scratch.md
24 changes: 12 additions & 12 deletions src/core/utils/computeExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand All @@ -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;
Expand All @@ -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);
}
Expand Down

0 comments on commit b51f443

Please sign in to comment.