Template framework can bind events on the root of views, in addition to descendant elements.

This commit is contained in:
Corey Johnson & Nathan Sobo
2011-12-29 16:13:16 -08:00
parent 5aee51eb35
commit 0f772c0858
2 changed files with 14 additions and 3 deletions

View File

@@ -13,7 +13,7 @@ describe "Template", ->
template = class extends Template
content: (attrs) ->
@div =>
@div keydown: 'viewClicked', class: 'rootDiv', =>
@h1 { outlet: 'header' }, attrs.title
@list()
@subview 'subview', subviewTemplate.build(title: "Subview")
@@ -29,6 +29,7 @@ describe "Template", ->
foo: "bar",
li1Clicked: ->,
li2Keypressed: ->
viewClicked: ->
view = template.build(title: "Zebra")
@@ -57,6 +58,10 @@ describe "Template", ->
expect(view.subview.header).toMatchSelector "h2"
it "binds events for elements with event name attributes", ->
spyOn(view, 'viewClicked').andCallFake (event, elt) ->
expect(event.type).toBe 'keydown'
expect(elt).toMatchSelector "div.rootDiv"
spyOn(view, 'li1Clicked').andCallFake (event, elt) ->
expect(event.type).toBe 'click'
expect(elt).toMatchSelector 'li.foo:contains(one)'
@@ -65,6 +70,9 @@ describe "Template", ->
expect(event.type).toBe 'keypress'
expect(elt).toMatchSelector "li.bar:contains(two)"
view.keydown()
expect(view.viewClicked).toHaveBeenCalled()
view.li1.click()
expect(view.li1Clicked).toHaveBeenCalled()
expect(view.li2Keypressed).not.toHaveBeenCalled()

View File

@@ -40,8 +40,11 @@ class Template
bindEvents: (view) ->
for eventName in this.constructor.events
view.find("[#{eventName}]").each ->
selector = "[#{eventName}]"
elements = view.find(selector).add(view.filter(selector))
elements.each ->
elt = $(this)
methodName = elt.attr(eventName)
elt[eventName]((event) -> view[methodName](event, elt))
elt.on eventName, (event) -> view[methodName](event, elt)