0

我想在添加到主干中的集合时自动生成模型属性。我做了一些搜索,但似乎找不到有关如何正确处理客户端生成的时间戳的任何信息。我的以下示例有效。(但可能并非在所有情况下)有没有更好的方法来使用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);
4

1 回答 1

4

我只是设置模型,以便在创建它时给它一个时间戳。因此,我会将以下内容添加到您的模型中:

var modelMessage = Backbone.Model.extend({
  defaults: function() {
    return {
      addedon: new Date().getTime()
    };
  },
  // ... the rest of your code
});

然后将Messages.listenTo调用更改为以下内容:

Messages.listenTo(Messages, "add", function (model) {
  model.set({levelcode: model.levelToInt()});
  $('#output').append('<div>added model:' + JSON.stringify(model.toJSON()) + '</div>');
});

这是一个小提琴:http: //jsfiddle.net/xUyak/

或者正如安德鲁提到的那样,以下内容也可以:

var modelMessage = Backbone.Model.extend({
  initialize: function() {
    this.set({
       addedon: new Date().getTime(),
       levelcode: this.levelToInt()
    });
  },
  // ... the rest of your code
});

然后你会model.set省略Message.listenTo

Messages.listenTo(Messages, "add", function (model) {
  $('#output').append('<div>added model:' + JSON.stringify(model.toJSON()) + '</div>');
});
于 2013-07-24T21:27:56.060 回答