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

feat dynamic event handler #3836

Merged

Conversation

tanhauhau
Copy link
Member

Fix #3040

Note: I've taken this chance to move the EventHandler rendering logic into render_dom/ folder.

@Rich-Harris
Copy link
Member

Excellent, this is a much-needed bugfix. I was wondering about an alternative approach — given the same input...

<script>
	let clickHandler;
	function updateHandler2(){
		clickHandler = () => number = 2;
	}
</script>

<button on:click={clickHandler}>click</button>

...what if we just wrapper the listen argument in a function, only in cases where the value is dynamic?

function create_fragment(ctx) {
	var button, dispose;

	return {
		c() {
			button = element("button");
			button.textContent = "click";
-			dispose = listen(button, "click", ctx.clickHandler);
+			dispose = listen(button, "click", function(e) {
+				ctx.clickHandler.call(this, e);
+			});
		},

It would require maintain_context to be true for that block, but I think it would result in better performance in pathological cases (where addEventListener and removeEventListener could be getting called very frequently) and slightly less code. Thoughts?

@tanhauhau
Copy link
Member Author

tanhauhau commented Nov 6, 2019

This is exactly the workaround I suggested for now.

Yea i think it's a good idea, why didnt i think of it in the first place?

@tanhauhau tanhauhau force-pushed the tanhauhau/dynamic-event-handler branch from 5a8fa4d to 105919e Compare November 6, 2019 16:39
@tanhauhau
Copy link
Member Author

i've make sure it works for component event handler as well.

@Rich-Harris Rich-Harris merged commit 60f7f79 into sveltejs:master Nov 6, 2019
@Rich-Harris
Copy link
Member

sweet. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Change event handler dynamically
2 participants