remove stuff that got moved to api page

This commit is contained in:
Leo Horie 2015-04-06 22:54:00 -04:00
parent d5619d412e
commit 6abb868c6b

View file

@ -2,13 +2,6 @@
---
- [Stateless components](#stateless-components)
- [Stateful components](#stateful-components)
- [Parameterized initial state](#parameterized-initial-state)
- [Data-driven component identity](#data-driven-component-identity)
- [Unloading components](#unloading-components)
- [Asynchronous components](#asynchronous-components)
- [Component limitations and caveats](#component-limitations-and-caveats)
- [Application architecture with components](#application-architecture-with-components)
- [Aggregation of responsibility](#aggregation-of-responsibility)
- [Distribution of concrete responsibilities](#distribution-of-concrete-responsibilities)
@ -20,284 +13,6 @@
---
Components are self-contained units of functionality that may hold state and communicate with a larger application via input parameters and events.
In Mithril, components are nothing more than [modules](mithril.module.md). In order to use a module as a component, simply put it in a template:
```javascript
//first declare a component (it's really just a module)
var MyComponent = m.component({
controller: function() {
return {greeting: "Hello"}
},
view: function(ctrl) {
return m("p", ctrl.greeting)
}
})
//now use it in an app
var MyApp = m.component({
controller: function() {},
view: function() {
return m("div", [
m("h1", "My app"),
MyComponent()
])
}
})
m.module(document.body, MyApp)
/*
<body>
<h1>My app</h1>
<p>Hello</p>
</body>
*/
```
Modules can have arguments "preloaded" into them. Calling `m.module` without a DOM element as an argument will create copy of the module with parameters already bound as arguments to the controller and view functions
```javascript
//declare a component
var MyComponent = m.component({
controller: function(args, extras) {
console.log(args.name, extras)
return {greeting: "Hello"}
},
view: function(ctrl, args, extras) {
return m("h1", ctrl.greeting + " " + args.name + " " + extras)
}
})
//note the lack of a DOM element in the list of parameters
var LoadedModule = m.module(MyModule, {name: "world"}, "this is a test")
var ctrl = new LoadedModule.controller() // logs "world", "this is a test"
m.render(document.body, LoadedModule.view(ctrl))
//<body><h1>Hello world this is a test</h1></body>
```
This way, we can create parameterized modules that look similar to regular virtual elements:
```javascript
var MyApp = {
controller: function() {},
view: function() {
return m("div", [
m("h1", "My app"),
//a parameterized module
m.module(MyModule, {name: "users"}, "from component"),
])
}
}
m.module(document.body, MyApp)
/*
<body>
<h1>My app</h1>
<h1>Hello users from component</h1>
</body>
*/
```
Since m.module can take any number of arguments, components also support more complex signatures if needed.
Note that adding a `key` property in the list of attributes (`{name: "users"}` above) will propagate this key to the root element of the component's template even if you don't manually do so. This allows all components to be identifiable without intervention from component authors.
---
### Dealing with state
#### Stateless components
A component is said to be stateless when it does not store data internally. Instead, it's composed of [pure functions](http://en.wikipedia.org/wiki/Pure_function). It's a good practice to make components stateless because they are more predictable, and easier to reason about, test and troubleshoot.
The previous section explained that components controllers can receive arguments passed to the `m.module` call, but this does not mean controllers are a necessary middle man in a component.
Instead of copying arguments to the controller object (thereby creating internal state in the component), and then passing the controller object to the view, it is often desirable that views always update based on the most current list of arguments being passed to a component.
The following example illustrates this pattern:
```javascript
var MyApp = {
controller: function() {
return {temp: m.prop(10)} //kelvin
},
view: function(ctrl) {
return m("div", [
m("input", {oninput: m.withAttr("value", ctrl.temp), value: ctrl.temp()}), "K",
m("br"),
m.module(TemperatureConverter, {value: ctrl.temp()})
]);
}
};
var TemperatureConverter = {
controller: function() {
//note how the controller does not handle the input arguments
//define some helper functions to be called from the view
return {
kelvinToCelsius: function(value) {
return value - 273.15
},
kelvinToFahrenheit: function(value) {
return (value 9 / 5 * (v - 273.15)) + 32
}
}
},
view: function(ctrl, args) {
return m('div', [
"celsius:", ctrl.kelvinToCelsius(args.value),
m("br"),
"fahrenheit:", ctrl.kelvinToFahrenheit(args.value),
]);
}
};
m.module(document.body, MyApp);
```
In the example above, the text input is bi-directionally bound to a `temp` getter-setter. Changing the temperature value from the input updates the temperature value, which is passed to the TemperatureConverter view directly, and transformation functions are called from there. The TemperatureConverter controller never stores the value.
Testing the various parts of the component is trivial:
```javascript
//test a transformation function in the controller
var ctrl = new TemperatureConverter();
assert(ctrl.kelvinToCelsius(273.15) == 0)
//test the template
var tpl = TemperatureConverter.view(null, {value: 273.15})
assert(tpl.children[1] == 0)
//test with real DOM
var testRoot = document.createElement("div")
m.render(testRoot, TemperatureConverter.view(null, {value: 273.15}))
assert(testRoot.innerHTML.indexOf("celsius:0") > -1)
```
Note that the sample component above is illustrative. Ideally, temperature conversion functions (and any functions that deal strictly within the domain of the data) should go in the model layer, not in a component's controller.
---
### Stateful components
Usually it's recommended that you store application state outside of components (either in a view-model or at the top-level module). Components can be stateful, but the purpose of component state is to prevent the pollution of the model layer with aspects that are inherently about the component. For example, an autocompleter component may need to internally store a flag to indicate whether the dropdown is visible, but this kind of state is not relevant to an application's business logic.
You may also elect to use component state for application state that is not meaningful outside the scope of a single component. For example, you might have a `UserForm` component that lives alongside other unrelated components on a bigger page, but it probably doesn't make sense for the parent page to be aware of the unsaved user entity stored within the `UserForm` component.
---
#### Parameterized initial state
The ability to handle arguments in the controller is useful for setting up the initial state for a component whose state depends on input data:
```javascript
var MyComponent = {
controller: function(args) {
//we only want to make this call once
return {
things: m.request({method: "GET", url: "/api/things/", {data: args}}) //slice the data in some way
}
},
view: function(ctrl) {
return m("ul", [
ctrl.things().map(function(name) {
return m("li", thing.name)
})
]);
}
};
```
However, it's recommended that you aggregate all of your requests in a single place instead of scattering them across multiple components. Aggregating requests in a top-level module makes it easier to replay the request chain (for example, you may need to fetch an updated list of items after you've saved something related to it) and it ensures the entire data set is loaded in memory before drilling down into the components (thus preventing the need for redundant AJAX calls for sibling components that need the same data). Be sure to read the [Application Architecture section](#application-architecture-with-components) to learn more about organizing componentized code.
#### Data-driven component identity
A component can be re-initialized from scratch by changing the `key` associated with it. This is useful for re-running ajax calls for different model entities.
```javascript
var people = [
{id: 1, name: "John"},
{id: 2, name: "Mary"}
]
//ajax and display a list of projects for John
m.render(document.body, m.module(ProjectList, {key: people[0].id, value: people[0]})
//ajax and display a list of projects for Mary
//here, since the key is different, the ProjectList component is recreated from scratch, which runs the controller, re-generates the DOM, and re-initializes any applicable 3rd party plugins in configs
m.render(document.body, m.module(ProjectList, {key: people[1].id, value: people[1]})
```
Note that the rules for keys apply for components the same way they do for regular elements: it is not allowed to have duplicate keys as children of the same parent, and they must be either strings or numbers (or something with a `.toString()` implementation that makes the entity locally uniquely identifiable when serialized). You can learn more about keys [here](mithril.md#dealing-with-focus)
---
### Unloading components
Modules declared in templates can also call `onunload` and its `e.preventDefault()` like regular modules. The `onunload` event is called if an instantiated module is removed from a virtual element tree via a redraw.
In the example below, clicking the button triggers the component's `onunload` event and logs "unloaded!".
```javascript
var MyApp = m.component({
controller: function() {
return {loaded: true}
},
view: function(ctrl) {
return m("div", [
m("button[type=button]", {onclick: function() {ctrl.loaded = false}}),
ctrl.loaded ? m.module(MyComponent) : ""
])
}
})
var MyComponent = m.component({
controller: function() {
return {
onunload: function() {
console.log("unloaded!")
}
}
},
view: function() {
return m("h1", "My component")
}
})
m.module(document.body, MyApp())
```
Calling `e.preventDefault()` from a component's `onunload` aborts route changes, but it does not abort, rollback or affect the current redraw in any way.
---
### Asynchronous components
Since components are Mithril modules, it's possible to encapsulate asynchronous behavior. Under regular circumstances, Mithril waits for all asynchronous tasks to complete, but when using components, a component's parent view renders before the component completes its asynchronous tasks (because the existence of the component only becomes known to the diff engine at the time when the template is rendered).
When a component has asynchronous payloads and they are queued by the [auto-redrawing system](auto-redrawing.md), its view is NOT rendered until all asynchronous operations complete. When the component's asynchronous operations complete, another redraw is triggered and the entire template tree is evaluated again. This means that the virtual dom tree may take two or more redraws (depending on how many nested asynchronous components there are) to be fully rendered.
There are [different ways to organize components](#application-architecture-with-components) that can side-step the need for multiple redraws (although you could still force multiple redraws to happen by using the [`background`](mithril.request.md#rendering-before-web-service-requests-finish) and `initialValue` options in `m.request`.)
---
### Component limitations and caveats
There are a few caveats to using modules as components:
1. Component views must return a virtual element. Returning an array, a string, a number, boolean, falsy value, etc will result in an error.
2. Components cannot change `m.redraw.strategy` from the controller constructor (but they can from event handlers). It's recommended that you use the [`ctx.retain`](mithril.md#persising-dom-elements-across-route-changes) flag instead of changing the redraw strategy in controller constructors.
---
## Application architecture with components
Components are versatile tools to organize code and can be used in a variety of ways.