我想在添加到主干中的集合时自动生成模型属性。我做了一些搜索,但似乎找不到有关如何正确处理客户端生成的时间戳的任何信息。我的以下示例有效。(但可能并非在所有情况下)有没有更好的方法来使用backbone.js?这是下面代码的小提琴。
<div id="output"></div>
//javascript
var modelMessage = Backbone.Model.extend({
levelToInt: function () {
switch (this.get('level')) {
case "error":
return 3;
break;
case "warning":
return 2;
break;
case "info":
return 1;
break;
default:
return 0;
break;
}
}
});
var collectionMessages = Backbone.Collection.extend({
model: modelMessage,
url: "#"
});
var Messages = new collectionMessages();
Messages.listenTo(Messages, "add", function (model) {
if (!model.get('addedon')) {
model.set({
addedon: new Date().getTime(),
levelcode: model.levelToInt()
});
}
$('#output').append('<div>added model:' + JSON.stringify(model.toJSON()) + '</div>');
});
Messages.add({
level: "info",
text: "Life is good."
});
setTimeout(function () {
Messages.add({
level: "warning",
text: "you have been warned..."
});
}, 1000);
setTimeout(function () {
Messages.add({
level: "error",
text: "OMG something really bad happened!",
});
}, 2000);