Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created May 2, 2012 08:56
Show Gist options
  • Save assertchris/2575281 to your computer and use it in GitHub Desktop.
Save assertchris/2575281 to your computer and use it in GitHub Desktop.
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) ->
behavior = {
"label": label
"elements": [],
"scope": @scope
"options": options
}
if options.scope
behavior.scope = scope = document.id(options.scope)
elements = scope.getElements("[data-behaviors~=#{label}]")
elements.each((element) ->
behavior.elements.include(element)
behavior.options.onAdd.apply(element, [scope, namespace(element, label)])
)
return this
remove: (label) ->
behavior = @registry[label]
behavior.elements.each((element) ->
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) ->
if not behavior.elements.contains(element)
behavior.push(element)
behavior.options.onAdd.apply(element, [behavior.scope, namespace(element, behavior.label)])
)
behavior.elements.each((element) ->
if not elements.contains(element)
behavior.elements.erase(element)
behavior.options.onRemove.apply(element, [behavior.scope, namespace(element, behavior.label)])
)
return this
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment