Skip to content

Helpers and Extensions

pelonpelon edited this page Aug 25, 2015 · 24 revisions

A collection of extensions to vanilla Mithril that you might find useful.


View Helpers

Helpers that can make your view more succinct.

m.withValue = function (callback) {
  return m.withAttr('value', callback)
}

Component Helpers

Helpers that deal with components.

m.initComponent

This helper allows you to create an instance of a component and manage it yourself. Useful for when you want explicit control over your component's lifecycle, e.g. you want to control when your controller gets initialized.

m.initComponent = function (component, options, content) {
  var controller = new component.controller(options)
  controller.render = function (options2, content2) {
    return component.view(controller, options2 || options, content2 || content)
  }
  return controller
}

Example use:

var UserList = {
  controller: function () { ... }
  view: function () { ... }
}
var App = {
  controller: function () {
    var ctrl = this
    ctrl.userList = m.initComponent(UserList, { users: [...] })
  },
  view: function (ctrl) {
    return m('.app', [
      m('h1', "My App"),
      ctrl.userList.render()
    ])
  }
}

Network Extensions

Helpers that deal with AJAX requests and the like.

m.deferred.resolve

This simple helper allows you to mock a promise with a successful value. Useful for AJAX cache layers and mocking server responses.

m.deferred.resolve = function (value) {
  var deferred = m.deferred()
  deferred.resolve(value)
  return deferred.promise
}

m.deferred.reject

This simple helper allows you to mock a rejected promise. Useful for mocking server responses.

m.deferred.reject = function (value) {
  var deferred = m.deferred()
  deferred.reject(value)
  return deferred.promise
}

Router Helpers

Router Wrapper

var Router = function(module, name) {
    return {
        controller: function() {
        	// Do something generic like calling Google Analytics from here
        	console.log("Router", name);
            return new module.controller();
        },
        view: module.view
    };
};

m.route(document.getElementById("page"), "/", {
    "/": Router(app, "app"),
    "/project/:id": Router(project, "project")
});
Clone this wiki locally