Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Last active January 12, 2018 21:20
Show Gist options
  • Select an option

  • Save andrejewski/5455ccdef77122389b1ac8a7b5ff8415 to your computer and use it in GitHub Desktop.

Select an option

Save andrejewski/5455ccdef77122389b1ac8a7b5ff8415 to your computer and use it in GitHub Desktop.
A Can Map powered by a Raj runtime
import Component from 'can-component'
import {program} from './raj-can-map'
import Map from 'can-map' // or whatever Map-like thing
import stache from 'can-stache'
export default Component.extend({
tag: 'my-app',
template: stache(`
<p>{{count}}</p>
<button on:click="increment()">Increment</button>
<button on:click="decrement()">Decrement</button>
`),
ViewModel: program(Map, () => ({
init: [0],
update (msg, state) {
if (message === "increment") {
return [state + 1]
}
if (message === "decrement") {
return [state - 1]
}
},
view (state, dispatch) {
return {
count: state,
increment () { dispatch('increment') },
decrement () { dispatch('decrement') }
}
}
}))
})
var rajProgram = require('raj/runtime').program
var canReflect = require('can-reflect')
function assignMap (map, props) {
var isV2Map = !canReflect.isMapLike(map) && typeof map.attr === 'function'
if (isV2Map) {
map.attr(props, true)
} else {
canReflect.update(map, props)
}
}
exports.program = function program(mapClass, createApp) {
return mapClass.extend({
init: function (props) {
const app = createApp(props)
this._killProgram = rajProgram(Object.assign(
{},
app,
{
view: (state, dispatch) => {
assignMap(this, app.view(state, dispatch))
}
}
))
},
connectedCallback: function () {
return () => {
if (this._killProgram) {
this._killProgram()
this._killProgram = undefined
}
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment