Search code examples
routesmithril.js

Can i send json data to Mithril route from outside


For example i have next mitril routes.

m.route.prefix("#");
m.route(document.getElementById('main'), "/", {
"/": {
	render: function() {
		return m('h1','Hello from root');
	}
},
"/trackingController/:numbers": {
	render: function(data) {
		var data = JSON.parse("data");
		// then work with parsed data
		return m('h1', 'Hello from trackingController')
	}
}

Can i send json data to trackingController route from outside?


Solution

  • Yes, routes can interpolate parameters. In your example you have a :numbers parameter, and your code suggests you expect a JSON string.

    The way Mithril exposes data passed through entities is via the vnode interface's attrs property. In the case of route components and route resolvers (like you're using here), attrs is a map of the URL parameters.

    In this example I'm using encodeURIComponent to allow JSON to be introduced in the URL. I've made the render function log the parsed data received from the URI path and expose the current route, as well as a text box where you can edit the JSON structure and submit it to re-route and see the new results.

    m.route.prefix("#");
    m.route(document.getElementById('main'), "/trackingController/" + encodeURIComponent('[1,2]'), {
      "/trackingController/:numbers": {
        render: function(vnode) {
          console.log(
            'Received the following `numbers`:',
            JSON.parse(vnode.attrs.numbers)
          )
    
          return [
            m('h1', 'Hello from trackingController'),
    
            m('p', 'Current route is ',
              m('code', m.route.get())
            ),
    
            m('form', {
                onsubmit: function(e) {
                  e.preventDefault()
    
                  m.route.set(
                    "/trackingController/" +
                    encodeURIComponent(e.target.elements.input.value)
                  )
                }
              },
              m('textarea#input', {
                value: vnode.attrs.numbers,
                style: {
                  background: '#444',
                  color: '#eee',
                  display: 'block',
                  padding: '1em',
                },
              }),
    
              m('button', 'Go!')
            ),
          ]
        }
      }
    })
    <script src="https://unpkg.com/mithril/mithril.js"></script>
    <div id=main></div>