var stooges = [
{name: 'moe', age: 40},
{name: 'larry', age: 50},
{name: 'curly', age: 60}
];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};
所以返回curly
,因为他是最老的,他是上面集合的最大年龄。
P.S(年龄可能不是最好的例子)让我们神奇地说,larry
患有某种疾病,他每年衰老 12 岁,变成 62 岁,而 curly
> 才 61 岁,我如何检测这种变化?
在我的真实应用程序中,集合中的最大值会定期更改,我希望有一个可以检测更改的函数,以便我可以添加内容来通知用户最大值已发生更改。
我知道backbone.js已经更改了
、_previousAttributes
和其他方法,但它们似乎只返回实际的最大值,而不是之前的最大值。
编辑:我的主干代码中有一个方法可以获取最大值
getMax : function(attribute) {
var home = $('#main').attr('data-home'),
away = $('#main').attr('data-away')
return this.collection.max(function (player) {
return player.get("teamName") === home || player.get("teamName") === away? player.get(attribute) : 0;
}, this);
}
因此,如果我想获取集合中的最大属性,我会调用 this.getMax("points");
并使用它来确定谁是我的最大点领导者。
我不确定如何将旧值与更改后的值进行比较,例如。 “kevin”有 12 分,而“adam”有 10 分,“kevin”是当前的最高分,因此单击后我为 Adam 添加 3 分,他现在有“13”分,现在是领先者,而“kevin”是前一个领导者。
所以我不知道如何创建一个方法或语句来检测最大值是否有变化
编辑:更改处理程序
// 1 for one point
if(e.keyCode == 49 && !e.ctrlKey || e.keyCode == 97 && !e.ctrlKey) {
if(this.$el.hasClass('hover')) {
var addMake = parseInt(this.model.get('made_one')) + 1;
var addOnePoint = parseInt(this.model.get('points')) + 1;
this.model.save({made_one: addMake, points: addOnePoint});
feedCollection.create({
feedItem: 'made a freethrow',
playerName: this.model.get('playerName'),
teamName: this.model.get('teamName'),
facebookID: this.model.get('facebookID')
});
}
}
好吧,改变模型的实际事件是在一个单独的 View 中,它实际上是一个按键事件。我监听统计 View 中集合的任何更改,该 View 是处理最大值的 View 。在统计 View 中,每次发生变化时我都会渲染它,因此如果值确实发生变化,它会自动放置适当的最大值,但我不确定如何检测该变化 this.listenTo(this.collection, "change “,this.render);
。
最佳答案
您需要为集合创建一个排序函数
class People extends Backbone.Collection
comparator: (p1, p2) ->
if p1.get("age") > p2.get("age") then -1 else 1
var stooges =
{name: 'moe', age: 40}
{name: 'larry', age: 50}
{name: 'curly', age: 60}
people = new People(stooges)
# whenever age changes, the people's order will be changed accordingly
people.on "change", people.sort, people
# so people.at(0) will always be the biggest
# people.at(1) will be the last biggest
# keep a reference to highest
highest = people.at(0)
# whenever sort happened, go and check if the highest is changed
people.on "sort", ->
current_highest = people.at(0)
create_new_feed(highest) unless current_highest.cid is highest.cid
create_new_feed = (person)->
feeds.create({name: person.get("name")})
关于javascript - 从主干集合中获取实时最大值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21561772/