Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created August 16, 2012 13:49
Show Gist options
  • Select an option

  • Save assertchris/3370234 to your computer and use it in GitHub Desktop.

Select an option

Save assertchris/3370234 to your computer and use it in GitHub Desktop.
Declarative Behaviors (Moo/CS)
do ->
walk = (parts, value) ->
stack = {}
part = parts.shift()
if parts.length
stack[part] = walk(parts, value)
else
stack[part] = value
return stack
namespace = (element, label) ->
params = {}
key = "data-" + label + "-"
Array.each(element.attributes, (attribute) ->
name = attribute.name
if name.contains(key)
parts = name.replace(key, "").split("-")
Object.merge(params, walk(parts, element.get(name)))
)
return params
window.Behaviors = new Class({
"initialize": (scope) ->
@scope = scope
@registry = {}
return this
"add": (label, options) ->
@registry[label] = behavior = {
"label": label
"scope": @scope or document.id(document.body)
"options": options
"elements": []
}
if options.scope
behavior.scope = document.id(options.scope)
elements = behavior.scope.getElements("[data-behaviors~=" + label + "]")
elements.each((element) ->
behavior.elements.include(element)
behavior.options.onAdd and behavior.options.onAdd.apply(element, [behavior.scope, namespace(element, label)])
)
return this
"remove": (label) ->
behavior = @registry[label]
behavior.elements.each((element) ->
behavior.options.onRemove and behavior.options.onRemove.apply(element, [behavior.scope, namespace(element, label)])
)
delete @registry[label]
return this
"update": ->
Object.each(@registry, (behavior) ->
elements = behavior.scope.getElements("[data-behaviors~=" + behavior.label + "]")
elements.each((element) ->
behavior.options.onUpdate and behavior.options.onUpdate.applyapply(element, [behavior.scope, namespace(element, behavior.label)])
unless behavior.elements.contains(element)
behavior.elements.push(element)
behavior.options.onAdd and behavior.options.onAdd.apply(element, [behavior.scope, namespace(element, behavior.label)])
)
behavior.elements.each((element) ->
unless elements.contains(element)
behavior.elements.erase(element)
behavior.options.onRemove and behavior.options.onRemove.apply(element, [behavior.scope, namespace(element, behavior.label)])
)
return this
)
})
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment