【问题标题】:Backbone - Greater model attribute from collectionBackbone - 来自集合的更大模型属性
【发布时间】:2013-07-03 08:01:28
【问题描述】:

配合 我正在尝试从其包含的所有模型中的主干集合中获取更大的属性。

举个例子:

App.Models.Example = Backbone.Model.extend({    
    defaults: {
        total: 0,
        created_at: '0000-00-00',
        updated_at: '0000-00-00'
    }

});

App.Collections.Examples = Backbone.Collection.extend({
    model: App.Models.Example,
    url: 'examples'
});

var examples = new App.Collections.Examples();
examples.sync();

我需要得到的是更大的 created_at 字段。

我该怎么做?

谢谢!

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    我认为您是在要求从集合中检索具有最新created_at 日期的集合中的模型是吗?

    如果是这样,则使用下划线 max 函数,如下所示:

    var mostRecentDateModel = examples.max(function(model){ 
        return model.get("created_at"); 
    });
    
    // this prints the most recent date that you are after
    console.log(mostRecentDateModel.get("created_at"));
    

    您需要记住,如果您的模型的 created_at 属性不是 JavaScript 日期(它可能是字符串),max 函数可能不会返回您期望的结果。因此,确保它确实是一个 Date 和/或将其转换为一个可能是值得的。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2012-12-30
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2015-04-26
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多