2013-07-16 95 views
0

我已經得到了我的工作文件的copule,我試圖創建這種方法我有我的觀點骨幹骨幹聽衆似乎沒有被解僱

APPVIEW的監聽器。 js.coffee

namespace "happiness_kpi", (exports) -> 
    exports.appView = Backbone.View.extend 

    events: 
     "click #happy" : "selection" 

    selection: -> 
     console.log "selection was called" 

index.html.haml

%input{ :type => "image", :src => "/assets/smiley.jpg", :alt => "happy", :id => "happy" } 
%input{ :type => "image", :src => "/assets/undecided.jpg", :alt => "undecided", :id => "undecided" } 
%input{ :type => "image", :src => "/assets/sad.jpg", :alt => "sad", :id => "sad" } 

,這裏是我的規格:
app_view_spec.js.coffee

it "is called when one of the faces is clicked", -> 
    $("body").append('<input alt="happy" id="happy" src="/assets/smiley.jpg" type="image">') 
    $("body").append('<input alt="undecided" id="undecided" src="/assets/undecided.jpg" type="image">') 
    $("body").append('<input alt="sad" id="sad" src="/assets/sad.jpg" type="image">') 
    @subject.selection = sinon.spy() 

    $("#happy").click 

    sinon.assert.calledOnce(@subject.selection) 

我收到錯誤'錯誤:預計的間諜被調用一次,但被稱爲0次'任何人有任何想法,爲什麼事件沒有被觸發時,輸入被點擊?

在此先感謝。

+0

'點擊()'用括號可能觸發事件? – Tallmaris

回答

0

這麼多的研究和他的動手後,我似乎已經走到了一個答案。問題絕對是我將圖像附加到iframe的方式。問題在於測試似乎在iframe之外創建了一個新元素,並且對該頁面不可見。該$('#happy').click()正在執行正確,但是,它的東西,並沒有在iframe存在執行。

所以我的解決辦法:

app_view_spec.js.coffee

beforeEach -> 
    $("body").append('<div id="display"></div>') 

afterEach -> 
    $("body").append('<div id ="display"></div>').remove() 

it "is called when one of the faces is clicked", -> 
    @subject.emotionSelection = sinon.spy() 
    @subject.delegateEvents() 

    $("input#happy").click() 

    sinon.assert.calledOnce @subject.emotionSelection 

appView.js.coffee EL: '#display'

initialize: -> 
    @render() 

events: -> 
    'click #happy': @emotionSelection 

render: -> 
    @$el.html HandlebarsTemplates.faces() 

emotionSelection: -> 
    console.log "hello" 

我發現做這方式是一個更好的途徑,我只是附加我HAML到的iframe,而不是試圖在自己的每個圖像追加。學過的知識。謝謝您的幫助!

1

如果在調用click()時問題不是明顯的括號中的拼寫錯誤,那麼我在想的另一件事是Backbone中的事件被限制在View元素中。這意味着,一個視圖不能列出事件本身外發生的事情(這當然可以,但不能簡單地使用events對象)。

試着在你測試開始這樣做:

@subject.setElement($("body")); 

這將設置查看el$el body標籤,所以要附加您查看裏面實際上將圖像和事件將被觸發。

+0

我嘗試設置'@ subject.setElement($( 「身體」));'但是我得到的錯誤'el'和'$ el'是不確定的。我試圖在控制檯上擺弄它,但我沒有太多的運氣。我發現問題的一部分與我的模板有關,但我已經解決了這個問題,並回到了手頭的問題。 – ndland