Skip to content

Instantly share code, notes, and snippets.

@CarlMungazi
Last active July 26, 2017 17:01
Show Gist options
  • Save CarlMungazi/65f51f2e4383bc1bd5aa57f5995db7c0 to your computer and use it in GitHub Desktop.
Save CarlMungazi/65f51f2e4383bc1bd5aa57f5995db7c0 to your computer and use it in GitHub Desktop.
Recommendations from mithril's docs

Before reading a library or framework's source code, it's advisable to go through the documentation. Thankfully, mithril's size means reading through the main APIs is not that arduous a task. When reading the docs, you will often find notes from the authors detailing recommended ways of using the available features. This is useful when you read the source because you can more easily understand why certain bits of code exist. I've noted below five recommendations I came across during my latest round of reading the mithril docs. I found more than five but I'll go through the rest at a later time. The example code below each recommendation has been taken from the docs.

  1. Use CSS selectors for attributes with unchanging values and pass an attributes object for attributes with values that can change
m("div#hello") // static

m("a.link[href=/]", { 
	class: currentURL === "/" ? "selected" : ""
}, "Home") // dynamic
  1. Got a list of data? Use an array to iterate over it
var users = [
	{name: "John"},
	{name: "Mary"},
]

m("ul", users.map(function(u) { // <ul>
	return m("li", u.name)  //   <li>John</li>
				//   <li>Mary</li>
})) 
  1. Conditionally set the content in a mithril view by using a ternary operator
var isError = false

m("div", isError ? "An error occurred" : "Saved") // <div>Saved</div>
  1. Unmount a component on an element by using m.mount(element, null). This also cleans up Mithril's internal state. The code which does that can be found here. If you're feeling lazy, the function is below:
function(redrawService) {
	return function(root, component) {
		if (component === null) {
			redrawService.render(root, [])
			redrawService.unsubscribe(root)
			return
		}
		
		if (component.view == null && typeof component !== "function") throw new Error("m.mount(element, component) expects a component, not a vnode")
		
		var run = function() {
			redrawService.render(root, Vnode(component))
		}
		redrawService.subscribe(root, run)
		run()
	}
}
  1. When using m.route, improve the user's navigation experience by taking advantange of the history.pushState API to 'remember' the state of things such as large forms. If the user nagivates away for whatever reason, the form is filled in when they return to that page. Example in the mithril docs can be found here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment