【问题标题】:How to specify one attribute of a model inside a collection?如何在集合中指定模型的一个属性?
【发布时间】:2013-12-04 04:49:11
【问题描述】:
render: function () {
    news.fetchMyNews();

    for (var i = 1; i <= news.length; i++) {
        var newsData = news.get(i);
        var newsRow = JST["news/row"](newsData.attributes);
        $("#news_tbody").append(newsRow);
        if (newsData.is_read == 1) {
            this.$('tr').attr("class", "news_read");
        } else if (newsData.is_read == 0) {
            this.$('tr').attr("class", "news_unread");
        }
    }
}

在这段代码中,newsData.attributes 被很好地检索,我得到了呈现 3 行的表格。

但是,newsData.is_read 值没有被检索,并且根本没有错误消息,因此,行没有得到样式。

新闻是一个集合。

我想知道,这有什么问题? 我用于测试的 JSON 文件如下所示:

[{
    "id": 1,
    "_type": "friends",
    "message": "Your friend ...",
    "is_read": 1
},

{
    "id": 2,
    "_type": "friends",
    "message": "Your friend ...",
    "is_read": 0
},

{
    "id": 3,
    "_type": "other",
    "message": "User ...",
    "is_read": 1
}]

【问题讨论】:

  • 这不是fetchMyNews方法异步吗?
  • @undefined fetchMyNews: function() { this.fetch({async:false}); }
  • 您是否登录到newsData 到控制台查看它返回的内容?你试过newsData.get('is_read')吗?

标签: javascript jquery css backbone.js


【解决方案1】:

由于newsData 是获取其属性的模型,因此应使用.get('is_read')newsData.attributes.is_read

【讨论】:

  • 谢谢,有帮助!我怀疑这很容易! :)
  • @ArmanOspanov 不客气 :),请注意,对于遍历集合,您还可以使用 .each() 方法而不是 for 循环,Backbone 集合继承了 Underscore 的方法。 news.each(fn) 会起作用。
猜你喜欢
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 2017-09-12
  • 1970-01-01
相关资源
最近更新 更多