Riot.js: minimal observable example
HTML
<div id="test"></div>
<script type="riot/tag">
<test>
<p>{ message }</p>
this.message = 'some message';
</test>
</script>
<script>
/* Riot WIP, @license MIT, (c) 2015 Muut Inc. + contributors */
;(function(window) {
// 'use strict' does not allow us to override the events properties https://github.com/muut/riotjs/blob/dev/lib/tag/update.js#L7-L10
// it leads to the following error on firefox "setting a property that has only a getter"
//'use strict'
var riot = { version: 'WIP', settings: {} },
ieVersion = checkIE()
riot.observable = function(el) {
el = el || {}
var callbacks = {},
_id = 0
el.on = function(events, fn) {
if (typeof fn == 'function') {
fn._id = typeof fn._id == 'undefined' ? _id++ : fn._id
events.replace(/\S+/g, function(name, pos) {
(callbacks[name] = callbacks[name] || []).push(fn)
fn.typed = pos > 0
})
}
return el
}
el.off = function(events, fn) {
if (events == '*') callbacks = {}
else {
events.replace(/\S+/g, function(name) {
if (fn) {
var arr = callbacks[name]
for (var i = 0, cb; (cb = arr && arr[i]); ++i) {
if (cb._id == fn._id) { arr.splice(i, 1); i-- }
}
} else {
callbacks[name] = []
}
})
}
return el
}
// only single event supported
el.one = function(name, fn) {
function on() {
el.off(name, on)
fn.apply(el, arguments)
}
return el.on(name, on)
}
el.trigger = function(name) {
var args = [].slice.call(arguments, 1),
fns = callbacks[name] || []
for (var i = 0, fn; (fn = fns[i]); ++i) {
if (!fn.busy) {
fn.busy = 1
fn.apply(el, fn.typed ? [name].concat(args) : args)
if (fns[i] !== fn) { i-- }
fn.busy = 0
}
}
if (callbacks.all && name != 'all') {
el.trigger.apply(el, ['all', name].concat(args))
}
return el
}
return...
JavaScript
riot.mount('#test','test');