From 0f772c08585bfd2ce980a3379b82d3df1508ca97 Mon Sep 17 00:00:00 2001 From: Corey Johnson & Nathan Sobo Date: Thu, 29 Dec 2011 16:13:16 -0800 Subject: [PATCH] Template framework can bind events on the root of views, in addition to descendant elements. --- spec/stdlib/template-spec.coffee | 10 +++++++++- src/stdlib/template.coffee | 7 +++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/spec/stdlib/template-spec.coffee b/spec/stdlib/template-spec.coffee index badf97ccd..537e94c66 100644 --- a/spec/stdlib/template-spec.coffee +++ b/spec/stdlib/template-spec.coffee @@ -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() diff --git a/src/stdlib/template.coffee b/src/stdlib/template.coffee index ebdaaffcf..e3ffd8dc0 100644 --- a/src/stdlib/template.coffee +++ b/src/stdlib/template.coffee @@ -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)