Created
February 7, 2012 22:50
-
-
Save gvarela/1762669 to your computer and use it in GitHub Desktop.
Light weight DI for client side components in CoffeScript..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class window.Bindable | |
constructor: (context=$('body'), @dataKey='bindable')-> | |
@bindables = $("[data-#{@dataKey}]", context) | |
@instanceKey = "#{@dataKey}-instance" | |
bindAll: -> | |
@bind(el) for el in @bindables | |
getRefs: -> | |
$(bindable).data(@instanceKey) for bindable in @bindables | |
release: -> | |
for bindable in @bindables | |
bindable = $(bindable) | |
if instance = bindable.data(@instanceKey) | |
instance.release() if typeof instance?.release is 'function' | |
bindable.data(@instanceKey, null) | |
delete @bindables | |
@bindables = [] | |
bind: (el, dataKey=@dataKey) -> | |
el = $(el) | |
key = el.data(dataKey) | |
if _class = @constructor.getClass(key) | |
el.data( @instanceKey, new _class(el) ) | |
else | |
console?.error "Bindable for key: #{key} not found in Bindable.registry for instance", el | |
@getClass: (key) -> | |
@registry[key]?.class | |
@register: (key, klass) -> | |
@registry ?= {} | |
@registry[key] = { class: klass } | |
return null | |
Extending Spine Controllers
class Example extends Spine.Controller
events:
'click a': 'toggle'
constructor: (el)->
super el: $(el)
toggle: (e)->
e.preventDefault()
$(e.target).toggleClass('active')
Bindable.register 'example', Example
Note Spine.Controller has a default 'release' event handler of removing the bound element @el. To override that functionality you have to unbind release first.
@unbind 'release'
@bind 'release', -> console.log 'release'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bindable class
HTML
Startup the application