How to handle dates in Backbone?

后端 未结 3 1853
醉话见心
醉话见心 2021-02-14 11:31

I store dates in the DATETIME format in a MySQL database. When a model is fetched from the database, dates (in the DATETIME format) are converted to date objects in the model\'s

3条回答
  •  时光取名叫无心
    2021-02-14 12:05

    I'd do it one of two places:

    • On the server:

      This probably makes the most sense, since your server-side implementation is really the one that needs the DATETIME representation; your client code shouldn't have to care at all.

    • In toJSON() on your model:

      If you must do it on the client, override Backbone.Model's toJSON() for your model and update it there. Example:

      toJSON: function () {
          var json = Backbone.Model.prototype.toJSON.call(this);
          json.date = convertDate(this.get('date'));
          return json;
      }
      

      If you do this, you'll need to convert the date back, either in your model's initialize() or parse() function.

提交回复
热议问题