-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
627 lines (578 loc) · 38.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>m - Mithril</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css">
<!--<![endif]-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,400italic|Source+Code+Pro" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="assets/css/style.min.css">
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<header class="header">
<div class="container">
<nav id="main-menu" role="navigation">
<ul>
<li><a href="getting-started.html">Guide</a></li>
<li class="current"><a href="mithril.html">API</a></li>
<li><a href="community.html">Community</a></li>
<li><a href="http://lhorie.github.io/mithril-blog">Learn</a></li>
<li><a href="installation.html">Download</a></li>
<li><a href="http://github.com/lhorie/mithril.js" target="_blank">Github <i class="fa fa-github dx"></i></a></li>
</ul>
</nav>
<a class="logo" href="index.html">
<ul id="rings">
<li class="one"></li>
<li class="one alt"></li>
<li class="two"></li>
<li class="two alt"></li>
<li class="three"></li>
</ul>
<span>Mithril</span>
</a>
</div>
</header>
<main class="main container pure-g">
<div class="content pure-u-1 pure-u-md-2-3 pure-push-md-1-3 pure-u-lg-3-4 pure-push-lg-1-4">
<a class="edit-page" target="_blank" href="https://github.com/lhorie/mithril.js/blob/next/docs/mithril.md" title="Edit on GitHub"><i class="fa fa-pencil"></i></a>
<!-- BEGIN main content -->
<h1 id="m">m</h2>
<hr>
<ol class="toc">
<li><a href="#usage">Usage</a></li>
<li><a href="#binding-to-data">Binding to data</a></li>
<li><a href="#using-html-entities">Using HTML entities</a></li>
<li><a href="#accessing-the-real-dom-element">Accessing the real DOM element</a></li>
<li><a href="#persisting-config-data">Persisting config data</a></li>
<li><a href="#destructors">Destructors</a></li>
<li><a href="#persisting-dom-elements-across-route-changes">Persisting DOM elements across route changes</a></li>
<li><a href="#svg">SVG</a></li>
<li><a href="#dealing-with-focus">Dealing with focus</a></li>
<li><a href="#dealing-with-sorting-and-deleting-in-lists">Dealing with sorting and deleting in lists</a></li>
<li><a href="#component-shorthand">Component shorthand</a></li>
<li><a href="#signature">Signature</a></li>
<li><a href="#the-config-attribute">The <code>config</code> attribute</a></li>
</ol>
<hr>
<p>This is a convenience method to compose virtual elements that can be rendered via <a href="mithril.render.html"><code>m.render()</code></a>.</p>
<p>You are encouraged to use CSS selectors to define virtual elements. See "Signature" section for details.</p>
<hr>
<h2 id="usage">Usage</h2>
<p>You can use simple tag selectors to make templates resemble HTML:</p>
<pre><code class="lang-javascript">m("br"); //yields a virtual element that represents <br>
m("div", "Hello"); //yields <div>Hello</div>
m("div", {class: "container"}, "Hello"); //yields <div class="container">Hello</div>
</code></pre>
<p>Note that the output value from <code>m()</code> is not an actual DOM element. In order to turn the virtual element into a real DOM element, you must call <a href="mithril.render.html"><code>m.render()</code></a>.</p>
<pre><code class="lang-javascript">m.render(document.body, m("br")); //puts a <br> in <body>
</code></pre>
<p>You can also use more complex CSS selectors:</p>
<pre><code class="lang-javascript">m(".container"); //yields <div class="container"></div>
m("#layout"); //yields <div id="layout"></div>
m("a[name=top]"); //yields <a name="top"></a>
m("[contenteditable]"); //yields <div contenteditable></div>
m("a#google.external[href='http://google.com']", "Google"); //yields <a id="google" class="external" href="http://google.com">Google</a>
</code></pre>
<p>Each <code>m()</code> call creates a virtual DOM element, that is, a Javascript object that represents a DOM element, and which is eventually converted into one.</p>
<p>You can, of course, nest virtual elements:</p>
<pre><code class="lang-javascript">m("ul", [
m("li", "item 1"),
m("li", "item 2"),
]);
/*
yields
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
*/
</code></pre>
<hr>
<p>The CSS selector syntax (e.g. <code>a#google.external[href='http://google.com']</code>) is meant to be used for declaring static attributes in the element, i.e. attribute values that don't change dynamically when the user interacts with the app.</p>
<p>The <code>attributes</code> argument (i.e. the second parameter in the <code>m("div", {class: "container"}, "Hello")</code> example) is meant to be used for attributes whose values we want to dynamically populate.</p>
<p>For example, let's say that you're generating a link from an entry that comes from a web service:</p>
<pre><code class="lang-javascript">//assume the variable `link` came from a web service
var link = {url: "http://google.com", title: "Google"}
m("a", {href: link.url}, link.title); //yields <a href="http://google.com">Google</a>
</code></pre>
<p>Here's a less trivial example:</p>
<pre><code class="lang-javascript">var links = [
{title: "item 1", url: "/item1"},
{title: "item 2", url: "/item2"},
{title: "item 3", url: "/item3"}
];
m.render(document.body, [
m("ul.nav",
links.map(function(link) {
return m("li",
m("a", {href: link.url}, link.title)
);
})
)
]);
</code></pre>
<p>yields:</p>
<pre><code class="lang-markup"><body>
<ul class="nav">
<li><a href="/item1">item 1</a></li>
<li><a href="/item2">item 2</a></li>
<li><a href="/item3">item 3</a></li>
</ul>
</body>
</code></pre>
<p>As you can see, flow control is done with vanilla Javascript. This allows the developer to abstract away any aspect of the template at will.</p>
<hr>
<p>Note that you can use both Javascript property names and HTML attribute names to set values in the <code>attributes</code> argument, but you should pass a value of appropriate type. If an attribute has the same name in Javascript and in HTML, then Mithril assumes you're setting the Javascript property.</p>
<pre><code class="lang-javascript">m("div", {class: "widget"}); //yields <div class="widget"></div>
m("div", {className: "widget"}); //yields <div class="widget"></div>
m("button", {onclick: alert}); //yields <button></button>, which alerts its event argument when clicked
//note this uses the Javascript syntax (uppercase "O") for `readonly`
//in order to set the boolean javascript property instead of the HTML attribute
m("input", {readOnly: true}); //yields <input readonly />
//using the HTML attribute name will call `setAttribute`, which may not be what you want
m("input", {readonly: false}); //yields <input readonly="false" />, which is still readonly
</code></pre>
<hr>
<p>Note that you can use JSON syntax if the attribute name you are setting has non-alphanumeric characters:</p>
<pre><code class="lang-javascript">m("div", {"data-index": 1}); //yields <div data-index="1"></div>
</code></pre>
<p>You can set inline styles like this:</p>
<pre><code class="lang-javascript">m("div", {style: {border: "1px solid red"}}); //yields <div style="border:1px solid red;"></div>
</code></pre>
<p>Note that in order to keep the framework lean, Mithril does not auto-append units like <code>px</code> or <code>%</code> to any values. Typically, you should not even be using inline styles to begin with (unless you are dynamically changing them).</p>
<p>Mithril also does not auto-camel-case CSS properties on inline style attributes, so you should use the Javascript syntax when setting them via Javascript objects:</p>
<pre><code class="lang-javascript">m("div", {style: {textAlign: "center"}}); //yields <div style="text-align:center;"></div>
m("div", {style: {cssFloat: "left"}}); //yields <div style="float:left;"></div>
//this does not work
m("div", {style: {"text-align": "center"}});
m("div", {style: {float: "left"}});
</code></pre>
<p>You can find the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference">Javascript syntax for all the CSS rules here</a>.</p>
<p>You can, however, use CSS syntax when defining style rules as inline strings:</p>
<pre><code class="lang-javascript">m("div[style='text-align:center']"); //yields <div style="text-align:center;"></div>
</code></pre>
<p>One caveat of using the CSS syntax is that it clobbers the <code>style</code> attribute in the DOM element on redraws, so this syntax is not appropriate if you need to use it in conjunction with 3rd party tools that modify the element's style outside of Mithril's templates (e.g. via <code>config</code>, which is explained below)</p>
<hr>
<h2 id="binding-to-data">Binding to data</h2>
<p>In order to stay flexible, Mithril doesn't provide helpers for bi-directional bindings out of the box. However, bindings can be implemented easily:</p>
<pre><code class="lang-javascript">//a data store
var name = m.prop("")
//binding the data store in a view
m("input", {oninput: m.withAttr("value", name), value: name()})
</code></pre>
<p>In the code above, the <code>oninput</code> event handler updates the <code>name</code> getter-setter, and the Mithril auto-redrawing system redraws the template in order to update the displayed value. You can read more about the <a href="mithril.prop.html"><code>m.prop</code> getter-setter utility here</a> and the <a href="mithril.withAttr.html"><code>m.withAttr</code> event handler factory here</a>. You can also <a href="auto-redrawing.html">learn how the redrawing system works here</a>.</p>
<p>Note that Mithril always considers the model layer data to be canonical. This means that in the code below, the input on screen will overwritten by the model data any time a redraw happens:</p>
<pre><code class="lang-javascript">//note that we are not updating the value of the `name` getter-setter via an event handler
//redraws will always overwrite the current UI value with the value of `name()`
m("input", {value: name()})
</code></pre>
<p>Expressiveness can be achieved using standard refactoring techniques:</p>
<pre><code class="lang-javascript">//refactor the binding to a simple helper
var binds = function(prop) {
return {oninput: m.withAttr("value", prop), value: prop()}
}
//a data store
var name = m.prop("")
//binding the data store in a view
m("input", binds(name))
</code></pre>
<p>Here's an example of a more aggressive refactor:</p>
<pre><code class="lang-javascript">//refactor the binding to a simple helper
var input = function(prop) {
return m("input", {oninput: m.withAttr("value", prop), value: prop()})
}
//a data store
var name = m.prop("")
//binding the data store in a view
input(name)
</code></pre>
<p>Alternatively, you can also explore other techniques in order to achieve better <a href="http://lhorie.github.io/mithril-blog/asymmetrical-data-bindings.html">performance</a> and <a href="http://lhorie.github.io/mithril-blog/extending-the-view-language.html">expressiveness</a>.</p>
<hr>
<h2 id="using-html-entities">Using HTML entities</h2>
<p>By default, Mithril escapes HTML strings in order to help prevent XSS attacks.</p>
<pre><code class="lang-javascript">m("div", "&times;") //becomes <div>&amp;times;</div>
</code></pre>
<p>You can unescape trusted HTML strings by using <a href="mithril.trust.html"><code>m.trust</code></a></p>
<pre><code class="lang-javascript">m("div", m.trust("&times;")) //becomes <div>&times;</div>
</code></pre>
<hr>
<h3 id="accessing-the-real-dom-element">Accessing the real DOM element</h3>
<p>You can define a non-HTML-standard attribute called <code>config</code>. This special parameter allows you to call methods on the DOM element after it gets created.</p>
<p>This is useful, for example, if you declare a <code>canvas</code> element and want to use the Javascript API to draw:</p>
<pre><code class="lang-javascript">function draw(element, isInitialized, context) {
//don't redraw if we did once already
if (isInitialized) return;
var ctx = element.getContext("2d");
/* draws stuff */
}
var view = [
m("canvas", {config: draw})
]
//this creates the canvas element, and therefore, `isInitialized` is false
m.render(document.body, view);
//here, isInitialized is `true`
m.render(document.body, view);
</code></pre>
<p>One common way of using <code>config</code> is in conjunction with <a href="mithril.route.html"><code>m.route</code></a>, which is an unobtrusive extension to links that allow Mithril's routing system to work transparently regardless of which routing mode is used.</p>
<pre><code class="lang-javascript">//this link can use any of Mithril's routing system modes
//(i.e. it can use either the hash, the querystring or the pathname as the router implementation)
//without needing to hard-code any syntax (`#` or `?`) in the `href` attribute.
m("a[href='/dashboard']", {config: m.route}, "Dashboard");
</code></pre>
<p>The <code>config</code> mechanism can also be used to put focus on form inputs, and call methods that would not be possible to execute via the regular attribute syntax.</p>
<p>Also note that the <code>config</code> callback only runs after a rendering lifecycle is done. Therefore, you should not use <code>config</code> to modify controller and model values, if you expect these changes to render immediately. Changes to controller and model values in this fashion will only render on the next <code>m.render</code> or <code>m.mount</code> call.</p>
<p>You can use this mechanism to attach custom event listeners to controller methods (for example, when integrating with third party libraries), but you are responsible for making sure the integration with Mithril's autoredrawing system is in place. See the <a href="integration.html">integration guide</a> for more information.</p>
<p>You can also use it to attach events to other elements (for example, <code>window.onresize</code>), but you should remove such event handlers via <code>ctx.onunload</code> to avoid surprises.</p>
<hr>
<h3 id="persisting-config-data">Persisting config data</h3>
<p>The third argument for <code>config</code> allows you to map data to a virtual DOM element in a way that persists across redraws. This is useful when a <code>config</code> instantiates 3rd party classes and accesses the instance on redraws.</p>
<p>The example below shows a contrived redraw counter. In it, the count is stored in the context object and re-accessed on each redraw.</p>
<pre><code class="lang-javascript">function alertsRedrawCount(element, isInit, context) {
if (!isInit) context.count = 0
alert(++context.count)
}
m("div", {config: alertsRedrawCount})
</code></pre>
<hr>
<h3 id="destructors">Destructors</h3>
<p>If the <code>context</code> object that is passed to a <code>config</code> function has a property called <code>onunload</code>, this function will be called when the element gets detached from the document by Mithril's diff engine.</p>
<p>This is useful if there are cleanup tasks that need to be run when an element is destroyed (e.g. clearing <code>setTimeout</code>'s, etc)</p>
<pre><code class="lang-javascript">function unloadable(element, isInit, context) {
context.timer = setTimeout(function() {
alert("timed out!");
}, 1000);
context.onunload = function() {
clearTimeout(context.timer);
console.log("unloaded the div");
}
};
m.render(document, m("div", {config: unloadable}));
m.render(document, m("a")); //logs `unloaded the div` and `alert` never gets called
</code></pre>
<hr>
<h3 id="persisting-dom-elements-across-route-changes">Persisting DOM elements across route changes</h3>
<p>When using the <a href="mithril.route.html">router</a>, a route change recreates the DOM tree from scratch in order to unload plugins from the previous page. If you want to keep a DOM element intact across a route change, you can set the <code>retain</code> flag in the config's context object.</p>
<p>In the example below, there are two routes, each of which loads a component when a user navigates to their respective URLs. Both components use a <code>menu</code> template, which contains links for navigation between the two components, and an expensive-to-reinitialize element. Setting <code>context.retain = true</code> in the element's config function allows the span to stay intact after a route change.</p>
<pre><code class="lang-javascript">//a menu template
var menu = function() {
return m("div", [
m("a[href='/']", {config: m.route}, "Home"),
m("a[href='/contact']", {config: m.route}, "Contact"),
//an expensive-to-initialize DOM element
m("span", {config: persistent})
])
}
//a configuration that persists across route changes
function persistent(el, isInit, context) {
context.retain = true
if (!isInit) {
//only runs once, even if you move back and forth between `/` and `/contact`
doSomethingExpensive(el)
}
}
//components that use the menu above
var Home = {
controller: function() {},
view: function() {
return m("div", [
menu(),
m("h1", "Home")
])
}
}
var Contact = {
view: function() {
return m("div", [
menu(),
m("h2", "Contact")
])
}
}
m.route(document.body, "/", {
"/": Home,
"/contact": Contact
})
</code></pre>
<p>Note that even if you set <code>context.retain = true</code>, the element will still be destroyed and recreated if it is different enough from the existing element. An element is considered "different enough" if:</p>
<ul>
<li>the tag name changes, or</li>
<li>the list of HTML attributes changes, or</li>
<li>the value of the element's id attribute changes</li>
</ul>
<p>In addition, setting <code>context.retain = false</code> will also cause the element to be recreated, even if it is not considered different enough.</p>
<hr>
<h3 id="svg">SVG</h3>
<p>You can use Mithril to create SVG documents (as long as you don't need to support browsers that don't support SVG natively).</p>
<p>Mithril automatically figures out the correct XML namespaces when it sees an SVG island in the virtual DOM tree.</p>
<pre><code class="lang-javascript">m("svg[height='200px'][width='200px']", [
m("image[href='foo.jpg'][height='200px'][width='200px']")
])
</code></pre>
<hr>
<h3 id="dealing-with-focus">Dealing with focus</h3>
<p>The virtual DOM diffing algorithm has a weakness: a naive diff is not aware of the identity of DOM elements. In practice, this means performing operations like shifting an item from the beginning of a list would cause every element in the list to be diffed and potentially recreated. Another side-effect is that UI state like input focus is not tracked correctly if the focused element moves around, and likewise, state for 3rd party plugins that are added via <code>config</code> can also end up in the wrong element.</p>
<p>Fortunately, with Mithril, it's possible for developers to attach an identity key to elements so that array operations like shift, splice and sort only affect the minimum amount of elements required, leaving the rest of the DOM elements untouched when a redraw happens. This allows us to maintain input focus and plugin state correctly.</p>
<p>To maintain the identities of DOM elements, you need to add a <code>key</code> property to the direct children of the array that you're planning to modify. The key for each child must be unique among a list of sibling DOM elements, but it does not need to be globally unique. Also, keys must be either strings or numbers.</p>
<pre><code class="lang-javascript">m("ul", [
items.map(function(item) {
return m("li", {key: item.id}, [
m("input")
]);
})
]);
</code></pre>
<p>In the example above, input focus would be maintained correctly after a redraw even if <code>items</code> got sorted or reversed. The key is defined in the <code>li</code>, which is the closest element to the <code>items</code> array, not directly on the <code>input</code>, even though we want to track focus on the input.</p>
<p>Note that in addition to the presence of the <code>key</code> attribute, diffing rules also apply in determining whether an element is recreated. Elements are recreated if either their node name changes, or if the list of attribute names change, or if the ID attribute changes. To avoid surprises, be sure to change only attribute values, using <code>undefined</code> or <code>null</code> as values if appropriate, rather than conditionally substituting attribute dictionaries altogether.</p>
<pre><code class="lang-javascript">//avoid using this idiom
m("li", selected ? {class: "active"} : {})
//use this idiom instead
m("li", {class: selected ? "active" : ""})
</code></pre>
<hr>
<h2 id="dealing-with-sorting-and-deleting-in-lists">Dealing with sorting and deleting in lists</h2>
<p>As with input focus, we can maintain referential integrity between data in a list and the respective DOM representation by using keys.</p>
<pre><code class="lang-javascript">m("ul", [
items.map(function(item) {
return m("li", {key: item.id}, [
m("input")
]);
})
]);
</code></pre>
<p>You should always use keys if you need to sort lists, remove items from them or splice them in any way.</p>
<hr>
<h2 id="component-shorthand">Component Shorthand</h2>
<p>If the first argument to <code>m()</code> is a component, it acts as an alias of <code>m.component()</code></p>
<pre><code class="lang-javascript">var MyComponent = {
controller: function() {
return {greeting: "hello"}
},
view: function(ctrl, args) {
return m("h1", ctrl.greeting + " " + args.data)
}
}
m.render(document.body, [
//the two lines below are equivalent
m(component, {data: "world"}),
m.component(component, {data: "world"})
])
</code></pre>
<p>See <a href="mithril.component.html">components</a> for more information.</p>
<hr>
<h2 id="signature">Signature</h2>
<p><a href="how-to-read-signatures.html">How to read signatures</a></p>
<pre><code class="lang-clike">VirtualElement m(String selector [, Attributes attributes] [, Children... children])
where:
VirtualElement :: Object { String tag, Attributes attributes, Children children }
Attributes :: Object<any | void config(DOMElement element, Boolean isInitialized, Object context, VirtualElement vdom)>
Children :: String text | VirtualElement virtualElement | Component | SubtreeDirective directive | Array<Children children>
Component :: Object { Function? controller, Function view }
SubtreeDirective :: Object { String subtree }
</code></pre>
<ul>
<li><p><strong>String selector</strong></p>
<p>This string should be a CSS rule that represents a DOM element.</p>
<p>Only tag, id, class and attribute selectors are supported.</p>
<p>If the tag selector is omitted, it defaults to <code>div</code>.</p>
<p>Note that if the same attribute is defined in the both <code>selector</code> and <code>attributes</code> parameters, the value in <code>attributes</code> is used.</p>
<p>For developer convenience, Mithril makes an exception for the <code>class</code> attribute: if there are classes defined in both parameters, they are concatenated as a space separated list. It does not, however, de-dupe classes if the same class is declared twice.</p>
<p><em>Examples:</em></p>
<p><code>"div"</code></p>
<p><code>"#container"</code></p>
<p><code>".active"</code></p>
<p><code>"[title='Application']"</code></p>
<p><code>"div#container.active[title='Application']"</code></p>
<p><code>".active#container"</code></p>
</li>
<li><p><strong>Attributes attributes</strong> (optional)</p>
<p>This key-value map should define a list of HTML attributes and their respective values.</p>
<p>You can use both HTML and Javascript attribute names. For example, both <code>class</code> and <code>className</code> are valid.</p>
<p>Values' types should match the expected type for the respective attribute.</p>
<p>For example, the value for <code>className</code> should be a string.</p>
<p>When a attribute name expects different types for the value in HTML and Javascript, the Javascript type should be used.</p>
<p>For example, the value for the <code>onclick</code> attribute should be a function.</p>
<p>Similar, setting the value of attribute <code>readonly</code> to <code>false</code> is equivalent to removing the attribute in HTML.</p>
<p>It's also possible to set values to Javascript-only properties, such as <code>hash</code> in a <code><a></code> element.</p>
<p>Note that if the same attribute is defined in the both <code>selector</code> and <code>attributes</code> parameters, the value in <code>attributes</code> is used.</p>
<p>For developer convenience, Mithril makes an exception for the <code>class</code> attribute: if there are classes defined in both parameters, they are concatenated as a space separated list. It does not, however, de-dupe classes if the same class is declared twice.</p>
<p><em>Examples:</em></p>
<p><code>{ title: "Application" }</code></p>
<p><code>{ onclick: function(e) { /*do stuff*/ } }</code></p>
<p><code>{ style: {border: "1px solid red"} }</code></p>
</li>
<li><h3 id="the-config-attribute">The <code>config</code> attribute</h3>
<p><strong>void config(DOMElement element, Boolean isInitialized, Object context, VirtualElement vdom)</strong> (optional)</p>
<p>You can define a non-HTML-standard attribute called <code>config</code>. This special parameter allows you to call methods on the DOM element after it gets created.</p>
<p>This is useful, for example, if you declare a <code>canvas</code> element and want to use the Javascript API to draw:</p>
<pre><code class="lang-javascript">function draw(element, isInitialized) {
//don't redraw if we did once already
if (isInitialized) return;
var ctx = element.getContext("2d");
/* draws stuff */
}
var view = [
m("canvas", {config: draw})
]
//this creates the canvas element, and therefore, `isInitialized` is false
m.render(document.body, view);
//here, isInitialized is `true`
m.render(document.body, view);
</code></pre>
<p>One common way of using <code>config</code> is in conjunction with <a href="mithril.route.html"><code>m.route</code></a>, which is an unobtrusive extension to links that allow Mithril's routing system to work transparently regardless of which routing mode is used.</p>
<pre><code class="lang-javascript">//this link can use any of Mithril's routing system modes
//(i.e. it can use either the hash, the querystring or the pathname as the router implementation)
//without needing to hard-code any syntax (`#` or `?`) in the `href` attribute.
m("a[href='/dashboard']", {config: m.route}, "Dashboard");
</code></pre>
<p>The <code>config</code> mechanism can also be used to put focus on form inputs, and call methods that would not be possible to execute via the regular attribute syntax.</p>
<p>Also note that the <code>config</code> callback only runs after a rendering lifecycle is done. Therefore, you should not use <code>config</code> to modify controller and model values, if you expect these changes to render immediately. Changes to controller and model values in this fashion will only render on the next <code>m.render</code> or <code>m.mount</code> call.</p>
<p>You can use this mechanism to attach custom event listeners to controller methods (for example, when integrating with third party libraries), but you are responsible for making sure the integration with Mithril's autoredrawing system is in place. See the <a href="integration.html">integration guide</a> for more information.</p>
<p>You can also use it to attach events to other elements (for example, <code>window.onresize</code>), but you should remove such event handlers via <code>ctx.onunload</code> to avoid surprises.</p>
<ul>
<li><strong>DOMElement element</strong></li>
</ul>
<p>The DOM element that corresponds to virtual element defined by the <code>m()</code> call.</p>
<ul>
<li><strong>Boolean isInitialized</strong></li>
</ul>
<p>Whether this is the first time we are running this function on this element. This flag is false the first time it runs on an element, and true on redraws that happen after the element has been created.</p>
<ul>
<li><strong>Object context</strong></li>
</ul>
<p>An object that retains its state across redraws. It can be used to store instances of 3rd party classes that need to be accessed more than one time throughout the lifecycle of a page.</p>
<p>The example below shows a contrived redraw counter. In it, the count is stored in the context object and re-accessed on each redraw.</p>
<pre><code class="lang-javascript">function alertsRedrawCount(element, isInit, context) {
if (!isInit) context.count = 0
alert(++context.count)
}
m("div", {config: alertsRedrawCount})
</code></pre>
<p>If the <code>context</code> object that is passed to a <code>config</code> function has a property called <code>onunload</code>, this function will be called when the element gets detached from the document by Mithril's diff engine.</p>
<p>This is useful if there are cleanup tasks that need to be run when an element is destroyed (e.g. clearing <code>setTimeout</code>'s, etc)</p>
<pre><code class="lang-javascript">function unloadable(element, isInit, context) {
context.timer = setTimeout(function() {
alert("timed out!");
}, 1000);
context.onunload = function() {
clearTimeout(context.timer);
console.log("unloaded the div");
}
};
m.render(document, m("div", {config: unloadable}));
m.render(document, m("a")); //logs `unloaded the div` and `alert` never gets called
</code></pre>
<ul>
<li><strong>VirtualElement vdom</strong></li>
</ul>
<p>The virtual DOM element to which the <code>config</code> function is attached</p>
</li>
<li><p><strong>Children children</strong> (optional)</p>
<p>If this argument is a string, it will be rendered as a text node. To render a string as HTML, see <a href="mithril.trust.html"><code>m.trust</code></a></p>
<p>If it's a VirtualElement, it will be rendered as a DOM Element.</p>
<p>If it's a <a href="mithril.component.html">component</a>, the component will be instantiated and managed internally by Mithril</p>
<p>If it's a list, its contents will recursively be rendered as appropriate and appended as children of the element being created.</p>
<p>If it's a SubtreeDirective with the value "retain", it will retain the existing DOM tree in place, if any. See <a href="mithril.render.html#subtree-directives">subtree directives.html</a> for more information.</p>
</li>
<li><p><strong>returns</strong> VirtualElement</p>
<p>The returned VirtualElement is a Javascript data structure that represents the DOM element to be rendered by <a href="mithril.render.html"><code>m.render</code></a></p>
</li>
</ul>
<!-- END main content -->
</div>
<div class="sidebar pure-u-1 pure-u-md-1-3 pure-pull-md-2-3 pure-u-lg-1-4 pure-pull-lg-3-4">
<h2 id="api">API <span class="version">v0.2.4</span> <a href="#">other versions...</a></h2>
<div class="sep"></div>
<ul class="sidebar-menu">
<li><strong id="core">Core</strong>
<ul>
<li class="current"><a href="mithril.html" title="A utility to create virtual elements">m</a></li>
<li><a href="mithril.component.html" title="Parameterizes a component">m.component</a></li>
<li><a href="mithril.mount.html" title="Renders a component">m.mount</a></li>
<li><a href="mithril.prop.html" title="A getter-setter utility">m.prop</a></li>
<li><a href="mithril.withAttr.html" title="A event handler factory utility">m.withAttr</a></li>
</ul>
</li>
<li><strong id="routing">Routing</strong>
<ul>
<li><a href="mithril.route.html" title="A routing utility">m.route</a>
<ul>
<li><a href="mithril.route.html#defining-routes" title="Defines what routes exist">m.route(rootElement, defaultRoute, routes)</a></li>
<li><a href="mithril.route.html#redirecting" title="Redirects to a route">m.route(path, params, replaceHistory)</a></li>
<li><a href="mithril.route.html#reading-current-route" title="Read the current route">m.route()</a></li>
<li><a href="mithril.route.html#mode-abstraction" title="Routing mode abstraction">m.route(element)</a></li>
<li><a href="mithril.route.html#mode" title="Whether routing uses location hash, querystring or pathname">m.route.mode</a></li>
<li><a href="mithril.route.html#param" title="Read an argument from a parameterized route">m.route.param</a></li>
<li><a href="mithril.route.html#buildQueryString" title="Serialize data into querystring format">m.route.buildQueryString</a></li>
<li><a href="mithril.route.html#parseQueryString" title="Read an argument from a parameterized route">m.route.parseQueryString</a></li>
</ul>
</li>
</ul>
</li>
<li><strong id="data">Data</strong>
<ul>
<li><a href="mithril.request.html" title="A high-level AJAX utility">m.request</a></li>
<li><a href="mithril.deferred.html" title="A Promise factory">m.deferred</a></li>
<li><a href="mithril.sync.html" title="A Promise aggregator">m.sync</a></li>
</ul>
</li>
<li><strong id="html">HTML</strong>
<ul>
<li><a href="mithril.trust.html" title="A method to unescape HTML">m.trust</a></li>
</ul>
</li>
<li><strong id="rendering">Rendering</strong>
<ul>
<li><a href="mithril.render.html" title="The lowest level rendering method">m.render</a></li>
<li><a href="mithril.redraw.html" title="A high-level explicit rendering method">m.redraw</a>
<ul>
<li><a href="mithril.redraw.html#strategy" title="A flag that drives the rendering strategy for the next redraw">m.redraw.strategy(strategy)</a></li>
</ul>
</li>
<li><a href="mithril.computation.html" title="Utilities to integrate asynchronous contexts to the rendering system">m.startComputation / m.endComputation</a></li>
</ul>
</li>
<li><strong id="data">Testing</strong>
<ul>
<li><a href="mithril.deps.html" title="The dependency injector">m.deps</a></li>
</ul>
</li>
<li><strong id="archive">History</strong>
<ul>
<li><a href="roadmap.html">Roadmap</a></li>
<li><a href="change-log.html">Change log</a></li>
</ul>
</li>
</ul>
</div>
</main>
<footer class="footer">
<div class="container pure-g">
<div class="pure-u-1-2">
<p>Released under the <a href="http://opensource.org/licenses/MIT" target="_blank">MIT license</a><br>
© 2014-2016 Leo Horie</p>
</div>
<div class="footer-dx pure-u-1-2">
<a href="http://github.com/lhorie/mithril.js" class="" title="Mithril on GitHub" target="_blank"><i class="fa fa-github"></i></a>
<a href="https://twitter.com/leohorie" class="" title="Mithril on Twitter" target="_blank"><i class="fa fa-twitter"></i></a>
</div>
</div>
</footer>
<a id="back-to-top" href="#main-menu" title="Scroll back to top">
<i class="fa fa-angle-up"></i>
</a>
<script src="assets/js/vendor/prism.js"></script>
<script src="assets/js/vendor/okay-nav.js"></script>
<script src="assets/js/vendor/smoothscroll.min.js"></script>
<script src="assets/js/scripts.min.js"></script>
<script src="https://use.fontawesome.com/eba026f8db.js"></script>
<!-- only for development, remove in production -->
<script type="text/javascript" src="//localhost:35729/livereload.js"></script>
</body>
</html>