Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created October 30, 2011 23:34
Show Gist options
  • Save dnagir/1326592 to your computer and use it in GitHub Desktop.
Save dnagir/1326592 to your computer and use it in GitHub Desktop.
Spine.js is not only for CRUD, it is also for TDD with JavaScript
href2selector = (href) -> href.match(/(#.+)/)[1]
class App.ContentSwitcher extends Spine.Controller
elements:
'li': 'items'
events:
'click li a': 'clickLink'
constructor: ->
super
@refresh()
clickLink: (e) ->
e.preventDefault()
@activateItem e.target
activateItem: (target) ->
active = $(target).closest('li')
all = active.parent().children()
all.removeClass('current')
active.addClass('current')
@refresh()
activeItem: -> @items.filter('.current')
contentItems: ->
selectors = @items.find('a').map -> href2selector(this.href)
$ selectors.toArray().join(', ')
activeContent: ->
activeSelector = href2selector @activeItem().find('a').prop('href')
$ activeSelector
refresh: ->
@contentItems().hide()
@activeContent().show()
describe "ContentSwitcher", ->
nav = null
beforeEach ->
setFixtures "
<div id='nav'>
<ul>
<li class='current'> <a href='#item1'>One</a> </li>
<li> <a href='#item2'>Twoo</a> </li>
<li> <a href='#item3'>Thre</a> </li>
</ul>
</div>
<div id='item1'> One </div>
<div id='item2'> Two </div>
<div id='item3'> Three </div>
"
nav = new App.ContentSwitcher el: '#nav'
it "should update the content initially", ->
expect($ "#item1").toBeVisible()
expect($ "#item2, #item3").toBeHidden()
it "should show related element", ->
$("#nav li").removeClass('current')
$("#nav li:last").addClass('current')
nav.refresh()
expect($ "#item3").toBeVisible()
expect($ "#item1, #item2").toBeHidden()
it "should activate when clicked", ->
spyOn(nav, 'refresh')
$("#nav li:last a").click()
expect(nav.refresh).toHaveBeenCalled()
<div id="side-nav">
<ul>
<li class='current'> <a href='#content1'>Content 1</a> <li>
<li> <a href='#content2'>Content 2</a> <li>
<li> <a href='#content3'>Content 3</a> <li>
</ul>
</div>
<div id='content1'>
Content 1
</div>
<div id='content2'>
Content 2
</div>
<div id='content3'>
Content 3
</div>
<script>
jQuery(function(){
new App.ContentSwitcher({el:"#side-nav"});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment