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

Adding click events to dom that was added via m.trust #2569

Open
omenking opened this issue Feb 12, 2020 · 3 comments
Open

Adding click events to dom that was added via m.trust #2569

omenking opened this issue Feb 12, 2020 · 3 comments

Comments

@omenking
Copy link

@omenking omenking commented Feb 12, 2020

Mithril version:
2.0.0-rc.9

Browser and OS:
Electron 8.0.0 (Chrome), macOS Sierra

Project:
https://github.com/ExamProCo/fast-author

Code

// Code

Context

I am creating a markdown editor.

Screen Shot 2020-02-12 at 1 52 28 PM

I am attempting to make it so that when I click an image in the preview I can process images eg. add a border, crop or etc.

So I render out my markdown and I use trust so I its can safely render.

m.trust(@md.render(Data.document()))

I need to make it so I can fire click events on the images.

I am thinking I can use onupdate(vnode), however I'm not sure how I would select the elements and bind click events by doing vnode.dom to all img elements contained within.

I can use document.querySelectorAll('.preview img') and attempt to bind click events through listeners but I imagine this is not a great idea since I would think those event listeners would become invalid on a redraw.

What is the mithril way for binding events that are from dynamic html?

@project-bot project-bot bot added this to Needs triage in Triage/bugs Feb 12, 2020
@danloomer
Copy link

@danloomer danloomer commented Feb 12, 2020

Could you maybe just keep the events at a higher level, like the element that contains the m.trust and then react to the event on that single handler based on the event.target?

Something like this.

@pygy
Copy link
Member

@pygy pygy commented Feb 13, 2020

You can use a fragment with an oncreate hook (resp. onupdate if needed):

m.render(document.body, m.fragment({
  oncreate({dom}){dom.onclick = () => console.log('clicked')}
}, [
  m.trust('<h1>Hi, click me')
]))

live

@isiahmeadows
Copy link
Member

@isiahmeadows isiahmeadows commented Feb 13, 2020

You might also want to consider just using innerHTML + attaching onclick listeners to the parent div or whatever + using ev.target.tagName/etc. to detect what's an image vs what's not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Triage/bugs
Needs triage
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.