Skip to content

Instantly share code, notes, and snippets.

@shama
Created April 27, 2015 00:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shama/33f7aaeb902a001637e8 to your computer and use it in GitHub Desktop.
Save shama/33f7aaeb902a001637e8 to your computer and use it in GitHub Desktop.
Data down, actions up idea module
var h = require('virtual-dom/h')
var xtend = require('xtend/mutable')
var merge = require('xtend')
function DownUp(data) {
if (!(this instanceof DownUp)) return new DownUp(data)
var self = this
this.set({
tagName: 'div',
childViews: [],
target: null,
actions: {},
}, data)
// Decorate _name to methods for super()
for (var method in this) {
if (typeof this[method] === 'function') {
this[method]._name = method
}
}
}
module.exports = DownUp
// Set the data
DownUp.prototype.set = function() {
var args = Array.prototype.slice.call(arguments)
args.unshift(this)
xtend.apply(xtend, args)
return this
}
// Toggle boolean values
DownUp.prototype.toggle = function(key) {
this[key] = (this[key]) ? false : true
return this
}
// Render the hyperscript
DownUp.prototype.render = function() {
return h(this.tagName, this, this.childViews)
}
// Send actions up
DownUp.prototype.send = function(name) {
var args = Array.prototype.slice.call(arguments, 1)
var actions = this.actions
var found = (typeof actions[name] === 'function')
if (typeof actions[name] === 'function') {
actions[name].apply(this, args)
return this
}
var target = this
while (target = target.target) {
if (!target) {
break
} else if (target.actions && typeof target.actions[name] === 'function') {
target.actions[name].apply(target, args)
return this
}
}
throw new Error('Could not find action: ' + name)
}
// Ability to call super() on methods
Object.defineProperty(DownUp.prototype, 'super', {
get: function get() {
var name = get.caller._name
var found = this[name] === get.caller
var proto = this
while (proto = Object.getPrototypeOf(proto)) {
if (!proto[name]) {
break
} else if (proto[name] === get.caller) {
found = true
} else if (found) {
return proto[name]
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment