Spine - Controllerの使い方
Spine のControllerとやらを試した
まず、基本的な機能
class Item extends Spine.Controller
# div element will be created if you don't create this instance like below.
# this 'tag' member can be skipped then it's 'div'
#
# new Item(el: $('selector'))
#
# if you created this instance like above,
# this instance handles the element you specified as 'el'.
tag: 'div'
constructor: ->
super # super.apply arguments blah blah
# @el is the element that this instance handles
console.log @el # [HTMLDivElement]
# and, it's a jQuery object, right?
console.log (@el instanceof jQuery) # true
# so, you can do jQuery things to @el
@el.css
'border': '3px solid purple'
'padding': '10px'
# @html replace the code inside @el
@html '<div class="hoge" style="color:red">Red!</div>'
# @append appends the code into @el
@append '<div class="foo" style="color:blue">Blue!</div>'
@append '<button>Buttonda</button>'
# @$('selector') is @el.find('selector')
console.log @$('.hoge').text() # Red!
console.log @$('.foo').text() # Blue!
# Controller has events.
# use bind with name and eventhandler
@bind 'myevent', ->
console.log 'oh yes, myevent was fired'
# easy to fire it
@trigger 'myevent' # oh yes, myevent was fired
# dom events to custom event.
# '=>' binds instance as 'this' in its eventhandler
button = @$('button')
button.click => @trigger 'myevent' # oh yes, myevent was fired
$ ->
# create Controller instance yey
item_a = new Item
# instance.el is the element which its instance handles
$('body').append(item_a.el)
# instance.appendTo is instance.el.appendTo
item_a.appendTo('#somewhere')
# when you created instance with {el: element},
# $('#testdiv') is instance.el.
# el can be selector string too.
item_b = new Item(el: $('#testdiv'))
以下、DOMイベントのバインドと中にある要素をメンバにサクッと登録する方法
class Item extends Spine.Controller
# 'events' sets delegatino event to @el. its syntax is...
# { 'domEventName selector' : methodNameAsEventHandler }
#
# follwoing does below
# @el.delegate '.button1', 'click', @button1clickHandler
# @el.delegate '.button2', 'click', @button2clickHandler
# @el.delegate '.button3', 'click', @button3clickHandler
events:
'click .button1': 'button1clickHandler'
'click .button2': 'button2clickHandler'
'click .button3': 'button3clickHandler'
# You may do things like
# @something = @$('.something')
# in constructor. Codes below does same thing
elements:
'.something': 'something'
# So, now it's clean constructor, isn't it?
# Maybe you had better to do template things with more smart way.
constructor: ->
super
@html '''
<div class="something">something</div>
<button class="button1">button1</button>
<button class="button2">button2</button>
<a class="button3" href="#">button3</a>
'''
button1clickHandler: -> console.log 'button1!'
button2clickHandler: -> console.log 'button2!'
button3clickHandler: (e) ->
e.preventDefault()
console.log 'button3!'
@something.fadeToggle()
$ ->
item = new Item
item.appendTo 'body'
まーフツーだ。特別コレ以上欲しい機能もないし。よくやることがメソッドになってる感
blog comments powered by Disqus