Search code examples
javascriptmithril.js

Setting an attribute dynamically in mithril.js


I'd like to set an attribute in mithril.js inside the oninit function. For example,

m('img', {
    oninit: (vnode) => {
        vnode.attrs.src = 'A url string';
    }
})

I want to check for certain conditions before setting this attribute and I'd rather not use the ternary operator because that would get messy. The above example half worked, on logging vnode, the attrs object has the correct src string, however in the DOM, src is set to null for some reason.

I'm looking for a simple solution and not something like, give an id to the element and use it to change the attribute.


Solution

  • Usually such code could be placed in the component as a method or as a function when using a closure component.

    This is in a component just for an image but such work could be done in a parent component that rendered that IMG directly.

    function DynamicImg() {
      function imageAttrs(vnode) {
        let src = 'configurable';
        return {src: src};
      }
      return {
        view: function (vnode) {
            return m('img', imageAttrs(vnode));
        }
      }
    }
    

    Setting an attr in init would not last as the view function would be called without it immediately. Since it is called at every render.