简体   繁体   中英

Add timestamp and sort order fields on collection add() Backbone.js

I want to automatically generate model attributes when added to a collection in backbone. I did some searching but can't seem to find any info on how to correctly handle timestamps generated on the client side. My following example works. (but probably not in all situations) Is there a better way to do this with backbone.js? Here is the fiddle for the code below.

<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);

I would just set up the model so that whenever it is created, you give it a timestamp. So I would add the following to your model:

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

Then change the Messages.listenTo call to the following as well:

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

Here is a fiddle: http://jsfiddle.net/xUyak/

Or as Andrew mentioned the following would work as well:

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

And then you would omit model.set in Message.listenTo :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM