Add ClosureComponent type

This commit is contained in:
spacejack 2019-01-01 18:04:14 -05:00
parent 570db36e68
commit f516c9be01
2 changed files with 43 additions and 2 deletions

View File

@ -244,6 +244,13 @@ declare namespace Mithril {
*/
type FactoryComponent<A = {}> = (vnode: Vnode<A>) => Component<A>;
/**
* Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse.
* Any function that returns an object with a view method can be used as a Mithril component.
* Components can be consumed via the m() utility.
*/
type ClosureComponent<A = {}> = FactoryComponent<A>;
/**
* Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse.
* Any Javascript object that has a view method is a Mithril component. Components can be consumed via the m() utility.

View File

@ -1,5 +1,5 @@
import m = require('mithril');
import { Component, FactoryComponent, Vnode } from 'mithril';
import * as m from 'mithril';
import { Component, ClosureComponent, FactoryComponent } from 'mithril';
///////////////////////////////////////////////////////////
// 0.
@ -50,6 +50,13 @@ const comp2: FactoryComponent<Comp2Attrs> = vnode => ({ // vnode is inferred
}
});
// 2a. Test ClosureComponent type alias
const comp2a: ClosureComponent<Comp2Attrs> = vnode => ({ // vnode is inferred
view({attrs: {title, description}}) { // Comp2Attrs type is inferred
return [m('h2', title), m('p', description)];
}
});
///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
@ -80,6 +87,31 @@ const comp3: FactoryComponent<{pageHead: string}> = () => ({
}
});
// 3.a Test ClosureComponent type alias
const comp3a: ClosureComponent<{pageHead: string}> = () => ({
oncreate({dom}) {
// Can do stuff with dom
},
view({attrs}) {
return m('.page',
m('h1', attrs.pageHead),
m(comp2,
{
// attrs is type checked - nice!
title: "A Title",
description: "Some descriptive text.",
onremove(vnode) {
console.log("comp2 was removed");
},
}
),
// Test other hyperscript parameter variations
m(comp1, m(comp1)),
m('br')
);
}
});
///////////////////////////////////////////////////////////
// 4.
// Stateful component using closure method & var
@ -152,7 +184,9 @@ m.route(document.body, '/', {
'/comp0': comp0,
'/comp1': comp1,
'/comp2': comp2,
'/comp2a': comp2a,
'/comp3': comp3,
'/comp3a': comp3a,
'/comp4': comp4,
'/comp5': comp5
});