Mithril.js: Adding click events to dom that was added via m.trust

Created on 12 Feb 2020  路  3Comments  路  Source: MithrilJS/mithril.js



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?

Question

All 3 comments

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.

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

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hadihammurabi picture hadihammurabi  路  4Comments

volnei picture volnei  路  3Comments

isiahmeadows picture isiahmeadows  路  4Comments

designMoreWeb picture designMoreWeb  路  4Comments

simov picture simov  路  4Comments