Skip to content

Instantly share code, notes, and snippets.

@simov
Created June 17, 2016 15:57
Show Gist options
  • Save simov/2280f023104fa4cbe119f0eb175a1c23 to your computer and use it in GitHub Desktop.
Save simov/2280f023104fa4cbe119f0eb175a1c23 to your computer and use it in GitHub Desktop.
Mithril.js persist dom elements on route change
// The `ul` element *is blinking*
var Navigation = {
controller: function () {
return {
config: (element, initialized, context) => {
context.retain = true
console.log(initialized)
}
}
},
view: (ctrl) => {
return m('ul', {config: ctrl.config}, [
m('li', m('a', {href: '/', config: m.route}, 'Home')),
m('li', m('a', {href: '/user/1', config: m.route}, 'User')),
m('li', m('a', {href: '/about', config: m.route}, 'About'))
])
}
}
var Home = {
view: (ctrl) => {
return [
m(Navigation),
m('h1', 'Home')
]
}
}
var User = {
view: () => {
return [
m(Navigation),
m('h1', 'User')
]
}
}
var About = {
view: () => {
return [
m(Navigation),
m('h1', 'About')
]
}
}
m.route(document.querySelector('body'), '/', {
'/': Home,
'/user/:id': User,
'/about': About
})
// The `ul` element is *not* blinking
var Navigation = {
view: (ctrl) => {
return m('ul', [
m('li', m('a', {href: '/', config: m.route}, 'Home')),
m('li', m('a', {href: '/user/1', config: m.route}, 'User')),
m('li', m('a', {href: '/about', config: m.route}, 'About'))
])
}
}
var Home = {
controller: function () {
m.redraw.strategy('diff')
},
view: () => {
return [
m(Navigation),
m('h1', 'Home')
]
}
}
var User = {
controller: function () {
m.redraw.strategy('diff')
},
view: () => {
return [
m(Navigation),
m('h1', 'User')
]
}
}
var About = {
controller: function () {
m.redraw.strategy('diff')
},
view: () => {
return [
m(Navigation),
m('h1', 'About')
]
}
}
m.route(document.querySelector('body'), '/', {
'/': Home,
'/user/:id': User,
'/about': About
})
// The `ul` element is *not* blinking
var isInitialized = false
var Navigation = {
view: (ctrl) => {
if (!isInitialized) {
isInitialized = true
return m('ul', [
m('li', m('a', {href: '/', config: m.route}, 'Home')),
m('li', m('a', {href: '/user/1', config: m.route}, 'User')),
m('li', m('a', {href: '/about', config: m.route}, 'About'))
])
}
else {
return {subtree: 'retain'}
}
}
}
var Home = {
view: () => {
return [
m(Navigation),
m('h1', 'Home')
]
}
}
var User = {
view: () => {
return [
m(Navigation),
m('h1', 'User')
]
}
}
var About = {
view: () => {
return [
m(Navigation),
m('h1', 'About')
]
}
}
m.route(document.querySelector('body'), '/', {
'/': Home,
'/user/:id': User,
'/about': About
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment