我正在尝试在以下主干视图上指定单击事件处理程序:
class ItemView extends Backbone.View
events:
"click": "addToCurrentlyFocusedList"
addToCurrentlyFocusedList: (e) =>
window.currentlyFocusedList.add @model
这就是我所拥有的:
describe "ItemView", ->
beforeEach ->
@item = new Backbone.Model
id: 1
name: "Item 1"
@view = new ItemView model: @item
describe "when clicked", ->
it "adds the item to the currently focused list", ->
window.currentlyFocusedList = sinon.stub()
window.currentlyFocusedList.add = sinon.stub()
@view.$el.trigger "click"
expect(window.currentlyFocusedList.add).toHaveBeenCalledWith @item
这行得通,但由于某种原因它困扰着我。也许感觉太像我在测试实现了。
我可以看到的一个可能的改进是将 click 事件处理程序、规范和 移动currentlyFocusedList
到一个名为的新视图中AppView
:
describe "AppView", ->
beforeEach ->
@view = new AppView
it "adds a clicked item to the currently focused list", ->
$clickedItem = @view.$(".item:first")
$clickedItem.trigger "click"
expect(@view.currentlyFocusedList.pluck('id')).toInclude $clickedItem.attr('data-id')
很好,这也消除了window
污染。它还测试该项目是否确实已添加到集合中。除此之外,移动事件处理程序和规范AppView
是否比我的第一种方法更好?有没有更好的方法来解决这个问题?