1

我正在构建一个待办事项应用程序,我有一个任务视图,它呈现一个任务模板,每个任务都有一个由用户选择的类别。每个任务都有一个 CategoryId 属性。我想显示每个任务的类别。所以我在任务视图中有以下功能:

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。然后该函数循环遍历每个类别并检查传递的 CategoryId 是否与 Category 集合中的某个类别的 id 匹配,然后返回匹配的类别的名称。但没有类别显示。所以我认为我没有正确返回类别的名称。当我在回调函数中 console.log 时,它会出现在控制台中,但不会返回。

你有什么想法?你能建议这个问题的解决方案吗?谢谢。

4

1 回答 1

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');
}
于 2013-03-07T17:57:01.403 回答