Skip to content

Commit

Permalink
support methods as actions (#5398)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanhauhau authored Sep 18, 2020
1 parent b3f54bd commit 254096d
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

* Support `use:obj.method` as actions ([#3935](https://github.com/sveltejs/svelte/issues/3935))
* Support `_` as numeric separator ([#5407](https://github.com/sveltejs/svelte/issues/5407))
* Fix assignments to properties on store values ([#5412](https://github.com/sveltejs/svelte/issues/5412))
* Support `import.meta` in template expressions ([#5422](https://github.com/sveltejs/svelte/issues/5422))
Expand Down
16 changes: 12 additions & 4 deletions src/compiler/compile/render_dom/wrappers/shared/add_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,19 @@ export function add_action(block: Block, target: string, action: Action) {

block.add_variable(id);

const fn = block.renderer.reference(action.name);
const [obj, ...properties] = action.name.split('.');

block.event_listeners.push(
x`@action_destroyer(${id} = ${fn}.call(null, ${target}, ${snippet}))`
);
const fn = block.renderer.reference(obj);

if (properties.length) {
block.event_listeners.push(
x`@action_destroyer(${id} = ${fn}.${properties.join('.')}(${target}, ${snippet}))`
);
} else {
block.event_listeners.push(
x`@action_destroyer(${id} = ${fn}.call(null, ${target}, ${snippet}))`
);
}

if (dependencies && dependencies.length > 0) {
let condition = x`${id} && @is_function(${id}.update)`;
Expand Down
8 changes: 8 additions & 0 deletions test/runtime/samples/action-object/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default {
html: `
<button>action</button>
`,
async test({ assert, target, window }) {
assert.equal(target.querySelector('button').foo, 'bar1337');
}
};
10 changes: 10 additions & 0 deletions test/runtime/samples/action-object/main.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script>
const obj = {
foo : "bar",
action(element, { leet }) {
element.foo = this.foo + leet;
},
}
</script>

<button use:obj.action={{ leet: 1337 }}>action</button>

0 comments on commit 254096d

Please sign in to comment.