2013-03-07 70 views
1

我正在構建一個待辦事項應用程序,我有任務視圖呈現任務模板,每個任務都有一個用戶選擇的類別。每個任務都有一個CategoryId屬性。我想顯示每個任務的類別。所以我在任務視圖以下功能:Backbone.js在模板中調用函數返回undefined

getCategoryName: function (categoryId) { 
    return app.Categories.each(function (category) { 
     if (categoryId === category.get('CategoryId')) { 
      return category.get('CategoryName'); 
     } 
    }); 
} 

這裏的任務模板:

<script type="text/template" id="taskTemplate"> 
<div class="view"> 
    <input class="toggle" type="checkbox" <%= Completed ? 'checked' : '' %> /> 
    <label class="title"><%- Description %></label> 
    <section class="info"> 
     <span class="category"><%- this.getCategoryName(CategoryId) %></span> 
    </section> 
    <button class="destroy"></button> 
</div> 
<input class="edit" value="<%- Description %>" /> 
</script> 

我所說的getCategoryName功能,並通過任務的類別編號。然後,該函數循環遍歷每個類別,並檢查傳遞的CategoryId是否與Category集合中某個類別的id相匹配,然後返回匹配的類別的名稱。但沒有類別顯示。所以我認爲我沒有正確地返回類別的名稱。當我console.log它在回調函數它出現在控制檯,但它不會返回。

你有什麼想法嗎?你能建議解決這個問題嗎? 謝謝。

回答

0

Collection.each實際上並沒有返回任何東西;它只是遍歷集合中的項目併爲每個項目執行回調函數。您應該使用Collection.find代替:

getCategoryName: function (categoryId) { 

    //find model that matches 
    var category = app.Categories.find(function (category) { 
    return categoryId === category.get('CategoryId'); 
    }); 

    //return the name if found, otherwise returns undefined 
    if(category) 
    return category.get('CategoryName'); 
} 
+0

謝謝!它現在正在工作,但是當我刷新頁面時,有時類別不會顯示在頁面上,有時候它們顯示正常。你能告訴我爲什麼會這樣嗎? – 2013-03-07 18:20:46

+0

@DimitarUzunov,也許有時你的'app.Categories'集合不包含任何要顯示的類別。聽起來這可能是一個併發問題 - 當你嘗試訪問它時,你的類別「fetch」還沒有完成。 – jevakallio 2013-03-07 18:22:59

+0

再次感謝。我在任務視圖之前初始化了類別視圖,現在似乎工作正常。 – 2013-03-07 18:29:28