Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve x-for reactivity #165

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 61 additions & 106 deletions dist/alpine-ie11.js

Large diffs are not rendered by default.

2,981 changes: 1,476 additions & 1,505 deletions dist/alpine.js

Large diffs are not rendered by default.

26 changes: 13 additions & 13 deletions src/component.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export default class Component {
})
}

walkAndSkipNestedComponents(el, callback, initializeComponentCallback = () => {}) {
walkAndSkipNestedComponents(el, callback, initializeComponentCallback = () => ({})) {
walk(el, el => {
// We've hit a component.
if (el.hasAttribute('x-data')) {
Expand All @@ -139,7 +139,7 @@ export default class Component {
})
}

initializeElements(rootEl, extraVars = () => {}) {
initializeElements(rootEl, extraVars = () => ({})) {
this.walkAndSkipNestedComponents(rootEl, el => {
// Don't touch spawns from for loop
if (el.__x_for_key !== undefined) return false
Expand Down Expand Up @@ -168,7 +168,7 @@ export default class Component {
this.resolveBoundAttributes(el, true, extraVars)
}

updateElements(rootEl, extraVars = () => {}) {
updateElements(rootEl, extraVars = () => ({})) {
this.walkAndSkipNestedComponents(rootEl, el => {
// Don't touch spawns from for loop (and check if the root is actually a for loop in a parent, don't skip it.)
if (el.__x_for_key !== undefined && ! el.isSameNode(this.$el)) return false
Expand Down Expand Up @@ -288,18 +288,18 @@ export default class Component {
})
}

evaluateReturnExpression(el, expression, extraVars = () => {}) {
return saferEval(expression, this.$data, {
...extraVars(),
$dispatch: this.getDispatchFunction(el),
})
evaluateReturnExpression(el, expression, extraVars = () => ({})) {
let extraVarsData = extraVars()
extraVarsData.$dispatch = this.getDispatchFunction(el)

return saferEval(expression, this.$data, extraVarsData)
}

evaluateCommandExpression(el, expression, extraVars = () => {}) {
return saferEvalNoReturn(expression, this.$data, {
...extraVars(),
$dispatch: this.getDispatchFunction(el),
})
evaluateCommandExpression(el, expression, extraVars = () => ({})) {
let extraVarsData = extraVars()
extraVarsData.$dispatch = this.getDispatchFunction(el)

return saferEvalNoReturn(expression, this.$data, extraVarsData)
}

getDispatchFunction (el) {
Expand Down
20 changes: 18 additions & 2 deletions src/directives/for.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,17 @@ export function handleForDirective(component, el, expression, initialUpdate, ext
delete currentEl.__x_for_key

let xForVars = {}
xForVars[single] = i
if (iterator1) xForVars[iterator1] = index
if (iterator2) xForVars[iterator2] = group
Object.defineProperty(xForVars, single, {
get() {
return i
},
set(newValue) {
items[index] = newValue
},
configurable: true
})
currentEl.__x_for = xForVars
component.updateElements(currentEl, () => {
return currentEl.__x_for
Expand Down Expand Up @@ -76,9 +84,17 @@ export function handleForDirective(component, el, expression, initialUpdate, ext
// Note we are resolving the "extraData" alias stuff from the dom element value so that it's
// always up to date for listener handlers that don't get re-registered.
let xForVars = {}
xForVars[single] = i
if (iterator1) xForVars[iterator1] = index
if (iterator2) xForVars[iterator2] = group
Object.defineProperty(xForVars, single, {
get() {
return i
},
set(newValue) {
items[index] = newValue
},
configurable: true
})
currentEl.__x_for = xForVars
component.initializeElements(currentEl, () => {
return currentEl.__x_for
Expand Down
8 changes: 4 additions & 4 deletions src/directives/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export function registerModelListener(component, el, modifiers, expression, extr
const listenerExpression = `${expression} = rightSideOfExpression($event, ${expression})`

registerListener(component, el, event, modifiers, listenerExpression, () => {
return {
...extraVars(),
rightSideOfExpression: generateModelAssignmentFunction(el, modifiers, expression),
}
let extraVarsData = extraVars()
extraVarsData.rightSideOfExpression = generateModelAssignmentFunction(el, modifiers, expression)

return extraVarsData
})
}

Expand Down
5 changes: 4 additions & 1 deletion src/directives/on.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ export function registerListener(component, el, event, modifiers, expression, ex

function runListenerHandler(component, expression, e, extraVars) {
return component.evaluateCommandExpression(e.target, expression, () => {
return {...extraVars(), '$event': e}
let extraVarsData = extraVars()
extraVarsData.$event = e

return extraVarsData
})
}

Expand Down
12 changes: 6 additions & 6 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,26 @@ export function debounce(func, wait) {
}

export function saferEval(expression, dataContext, additionalHelperVariables = {}) {
return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`))(
dataContext, ...Object.values(additionalHelperVariables)
return (new Function(['$data', '$extraVars'], `var result; with($extraVars) { with($data) { result = ${expression} } }; return result`))(
dataContext, additionalHelperVariables
)
}

export function saferEvalNoReturn(expression, dataContext, additionalHelperVariables = {}) {
// For the cases when users pass only a function reference to the caller: `x-on:click="foo"`
// Where "foo" is a function. Also, we'll pass the function the event instance when we call it.
if (Object.keys(dataContext).includes(expression)) {
let methodReference = (new Function(['dataContext', ...Object.keys(additionalHelperVariables)], `with(dataContext) { return ${expression} }`))(
dataContext, ...Object.values(additionalHelperVariables)
let methodReference = (new Function(['dataContext', '$extraVars'], `with($extraVars) { with(dataContext) { return ${expression} } }`))(
dataContext, additionalHelperVariables
)

if (typeof methodReference === 'function') {
return methodReference.call(dataContext, additionalHelperVariables['$event'])
}
}

return (new Function(['dataContext', ...Object.keys(additionalHelperVariables)], `with(dataContext) { ${expression} }`))(
dataContext, ...Object.values(additionalHelperVariables)
return (new Function(['dataContext', '$extraVars'], `with($extraVars) { with(dataContext) { ${expression} } }`))(
dataContext, additionalHelperVariables
)
}

Expand Down
28 changes: 26 additions & 2 deletions test/for.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Alpine from 'alpinejs'
import { wait } from '@testing-library/dom'
import { wait, fireEvent } from '@testing-library/dom'

global.MutationObserver = class {
observe() {}
Expand Down Expand Up @@ -69,7 +69,7 @@ test('removes all elements when array is empty and previously had multiple items
await wait(() => { expect(document.querySelectorAll('span').length).toEqual(0) })
})

test('elements inside of loop are reactive', async () => {
test('elements inside of loop are reactive - update from component context', async () => {
document.body.innerHTML = `
<div x-data="{ items: ['first'], foo: 'bar' }">
<button x-on:click="foo = 'baz'"></button>
Expand Down Expand Up @@ -97,6 +97,30 @@ test('elements inside of loop are reactive', async () => {
})
})

test('elements inside of loop are reactive - update from item context', async () => {
document.body.innerHTML = `
<div x-data="{ items: ['first', 'second'] }">
<template x-for="item in items">
<div>
<span x-text="item"></span>
<button x-on:click="item = 'foo'"></button>
</div>
</template>
</div>
`

Alpine.start()

expect(document.querySelectorAll('span')[0].innerText).toEqual('first')

document.querySelectorAll('button')[0].click()

await wait(() => {
expect(document.querySelectorAll('span')[0].innerText).toEqual('foo')
})
})


test('components inside of loop are reactive', async () => {
document.body.innerHTML = `
<div x-data="{ items: ['first'] }">
Expand Down