Mithril 2.0.0-rc.5

3rd Party Integration

Integration with third party libraries or vanilla JavaScript code can be achieved via lifecycle methods.

noUiSlider Example

/** NoUiSlider wrapper component */
function Slider() {
    var slider

    return {
        oncreate: function(vnode) {
            // Initialize 3rd party lib here
            slider = noUiSlider.create(vnode.dom, {
                start: 0,
                range: {min: 0, max: 100}
            })
            slider.on('update', function(values) {
                vnode.attrs.onChange(values[0])
                m.redraw()
            })
        },
        onremove: function() {
            // Cleanup 3rd party lib on removal
            slider.destroy()
        },
        view: function() {
            return m('div')
        }
    }
}

/** Demo app component */
function Demo() {
    var showSlider = false
    var value = 0

    return {
        view: function() {
            return m('.app',
                m('p',
                    m('button',
                        {
                            type: 'button',
                            onclick: function() {
                                showSlider = !showSlider
                            }
                        },
                        showSlider ? "Destroy Slider" : "Create Slider"
                    )
                ),
                showSlider && m(Slider, {
                    onChange: function(v) {
                        value = v
                    }
                }),
                m('p', value)
            )
        }
    }
}

m.mount(document.body, Demo)

Live Demo

Bootstrap FullCalendar Example

/** FullCalendar wrapper component */
var FullCalendar = {
    oncreate: function (vnode) {
        console.log('FullCalendar::oncreate')
        $(vnode.dom).fullCalendar({
            // put your initial options and callbacks here
        })
    },
    onremove: function (vnode) {
        // Run any destroy / cleanup methods here.
        $(vnode.dom).fullCalendar('destroy')
    },
    view: function (vnode) {
        return m('div')
    }
}

/** Demo app component */
function Demo() {
    var fullCalendarEl

    function next() {
        $(fullCalendarEl).fullCalendar('next')
    }

    function prev() {
        $(fullCalendarEl).fullCalendar('prev')
    }

    return {
        view: function (vnode) {
            return [
                m('h1', 'Calendar'),
                m(FullCalendar, {
                    oncreate: function(vnode) {
                        fullCalendarEl = vnode.dom
                    }
                }),
                m('button', {
                    onclick: prev
                }, 'Mithril Button -'),
                m('button', {
                    onclick: next
                }, 'Mithril Button +')
            ]
        }
    }
}

m.mount(document.body, Demo)

Live Demo


License: MIT. © Leo Horie.