Integrating with Other Libraries

Integration with third party libraries or vanilla javascript code can be achieved via the config attribute of virtual elements.

It’s recommended that you encapsulate integration code in a component or a helper function.

The example below shows a simple component that integrates with the select2 library.

  1. var Select2 = {
  2. // Returns a select box
  3. view: function(ctrl, attrs) {
  4. var selectedId = attrs.value().id;
  5. //Create a Select2 progrssively enhanced SELECT element
  6. return m("select", {config: Select2.config(attrs)}, [
  7. attrs.data.map(function(item) {
  8. var args = {value: item.id};
  9. // Set selected option
  10. if(item.id == selectedId) {
  11. args.selected = "selected";
  12. }
  13. return m("option", args, item.name);
  14. })
  15. ]);
  16. },
  17. /**
  18. Select2 config factory. The params in this doc refer to properties of the `ctrl` argument
  19. @param {Object} data - the data with which to populate the <option> list
  20. @param {prop} value - the prop of the item in `data` that we want to select
  21. @param {function(Object id)} onchange - the event handler to call when the selection changes.
  22. `id` is the the same as `value`
  23. */
  24. // Note: The config is never run server side.
  25. config: function(ctrl) {
  26. return function(element, isInitialized) {
  27. if(typeof jQuery !== 'undefined' && typeof jQuery.fn.select2 !== 'undefined') {
  28. var el = $(element);
  29. if (!isInitialized) {
  30. el.select2()
  31. .on("change", function(e) {
  32. var id = el.select2("val");
  33. m.startComputation();
  34. //Set the value to the selected option
  35. ctrl.data.map(function(d){
  36. if(d.id == id) {
  37. ctrl.value(d);
  38. }
  39. });
  40. if (typeof ctrl.onchange == "function"){
  41. ctrl.onchange(el.select2("val"));
  42. }
  43. m.endComputation();
  44. });
  45. }
  46. el.val(ctrl.value().id).trigger("change");
  47. } else {
  48. console.warn('ERROR: You need jquery and Select2 in the page');
  49. }
  50. };
  51. }
  52. };
  53. var Dashboard = {
  54. controller: function() {
  55. var ctrl = this,
  56. //list of users to show
  57. data = [
  58. {id: 1, name: "John"},
  59. {id: 2, name: "Mary"},
  60. {id: 3, name: "Seniqua"}
  61. ];
  62. ctrl.data = data;
  63. // Has to use a prop for the current user
  64. ctrl.currentUser = m.prop(data[1]);
  65. ctrl.changeUser = function(id) {
  66. console.log(id);
  67. };
  68. },
  69. view: function(ctrl) {
  70. return m("div", [
  71. m("label", "User:"),
  72. m.component(Select2, {
  73. data: ctrl.data,
  74. value: ctrl.currentUser,
  75. onchange: ctrl.changeUser
  76. })
  77. ]);
  78. }
  79. };
  80. m.mount(document.body, Dashboard);

select2.config is a factory that creates a config function based on a given controller. We declare this outside of the select2.view function to avoid cluttering the template.

The config function created by our factory only runs the initialization code if it hasn’t already. This if statement is important, because this function may be called multiple times by Mithril’s auto-redrawing system and we don’t want to re-initialize select2 at every redraw.

The initialization code defines a change event handler. Because this handler is not created using Mithril’s templating engine (i.e. we’re not defining an attribute in a virtual element), we must manually integrate it to the auto-redrawing system.

This can be done by simply calling m.startComputation at the beginning, and m.endComputation at the end of the function. You must add a pair of these calls for each asynchronous execution thread, unless the thread is already integrated.

For example, if you were to call a web service using m.request, you would not need to add more calls to m.startComputation / m.endComputation (you would still need the first pair in the event handler, though).

On the other hand, if you were to call a web service using jQuery, then you would be responsible for adding a m.startComputation call before the jQuery ajax call, and for adding a m.endComputation call at the end of the completion callback, in addition to the calls within the change event handler. Refer to the auto-redrawing guide for an example.

One important note about the config method is that you should avoid calling m.redraw, m.startComputation and m.endComputation in the config function’s execution thread. (An execution thread is basically any amount of code that runs before other asynchronous threads start to run.)

While Mithril technically does support this use case, relying on multiple redraw passes degrades performance and makes it possible to code yourself into an infinite execution loop situation, which is extremely difficult to debug.

The dashboard component in the example shows how a developer would consume the select2 component.

You should always document integration components so that others can find out what attribute parameters can be used to initialize the component.


Integrating to legacy code

If you need to add separate widgets to different places on a same page, you can simply initialize each widget as you would a regular Mithril application (i.e. use m.render, m.mount or m.route).

There’s just one caveat: while simply initializing multiple “islands” in this fashion works, their initialization calls are not aware of each other and can cause redraws too frequently. To optimize rendering, you should add a m.startComputation call before the first widget initialization call, and a m.endComputation after the last widget initialization call in each execution thread.

  1. m.startComputation()
  2. m.mount(document.getElementById("widget1-container"), Widget1)
  3. m.mount(document.getElementById("widget2-container"), Widget2)
  4. m.endComputation()