Routing solution to link URLs to Metal.js components using HTML5 History API.
import Component from 'metal-component';
import Router from 'metal-router';
class MyComponent extends Component {
...
};
Component.render(Router, {
component: MyComponent,
data: {
title: 'Home Page'
},
element: '#main > div',
path: '/path'
});
// Dispatch router to the current browser url
Router.router().dispatch();
<Router
component={MyComponent}
data={{
title: 'Home Page'
}}
path="/path"
/>
{call Router.render}
{param component: 'MyComponent' /}
{param data: ['title': 'Home Page'] /}
{param path: '/path' /}
{/call}
There are multiple ways to pass data to the component
.
The data
config property can be an object, or a function that can
return either an object or a promise. The following examples will
all return the same data to MyComponent
.
// Object literal
Component.render(Router, {
component: MyComponent,
data: {
title: 'Home Page'
},
path: '/path'
});
// Function
Component.render(Router, {
component: MyComponent,
data: function() {
return {
title: 'Home Page'
}
},
path: '/path'
});
// Promise
Component.render(Router, {
component: MyComponent,
data: function() {
return new Promise(function(resolve) {
resolve({
title: 'Home Page'
});
});
},
path: '/path'
});
If returning a promise, the component will not be rendered until the promise is resolved.
Data from an Ajax request can easily be passed to the component
via the fetch
and fetchUrl
config properties.
Component.render(Router, {
component: MyComponent,
fetch: true,
fetchUrl: '/some/api.json',
path: '/path'
});
This will fire off a request to /some/api.json
when /path
is navigated to,
and pass the returned data directly to MyComponent
. Note that the component
will not be rendered until the request is complete.
Use the fetchTimeout
property for setting a max amount of time
for the request.
Component.render(Router, {
component: MyComponent,
fetch: true,
fetchTimeout: 10000, // Milliseconds
fetchUrl: '/some/api.json',
path: '/path'
});
Params can be collected from the path and passed to the component
alongside
regular data.
Component.render(Router, {
component: MyComponent,
data: {
title: 'User Page'
},
path: '/user/:name'
});
Then if the user navigates to /user/foo
, the following data
will be passed to the component.
{
router: {
params: {
name: 'foo'
}
},
title: 'User Page'
}
Query params are also parsed and added to the component data. If the user navigates to `/user/foo?id=123', the following data will be passed to the component.
{
router: {
params: {
name: 'foo'
},
query: {
id: '123'
}
},
title: 'User Page'
}
-
Install a recent release of NodeJS if you don't have it yet.
-
Install local dependencies:
npm install
- Run the tests:
npm test
- Build the code:
npm run build
- Run the demo:
npm run demo
Check out the contributing guidelines for more information.