Search code examples
javascriptmithril.js

How does Mithril component work here is some weird experience I had


I was going through documentation and I ran following code in script.js

    var Article = {
    view: function(vnode) {
        console.log(vnode)
        return "This is article " + vnode.attrs.articleid
    }
}
m.route(document.body, '/article/:articleid' ,{
    '/article/:articleid': Article
})
m.route.set('/article/:articleid', {articleid: 1})

but to my surprise I got the vnode ds twice in console

Output


Solution

  • That’s because the router executes immediately when it’s defined (when you call m.route(…)), and then once again when you call m.route.set(…). The second argument to m.route(…) is the route that will resolve immediately, and the call to m.route.set(…) isn’t necessary to initialise routing— in this case you’ve kept the route parameter interpolation string, but it should be expressed literally:

    var Article = {
      view: function(vnode) {
        console.log(vnode)
          return "This is article " + vnode.attrs.articleid
      }
    }
    
    m.route(document.body, '/article/1' ,{
        '/article/:articleid': Article
      })