在ember.js记录上使用toJSON,将其中一个属性设置为null

Using toJSON on a ember.js record, is setting one of the attributes to null

本文关键字:一个 属性 null 设置 记录 js ember toJSON      更新时间:2024-03-09

我一直在摆弄ember.jstodoMVC示例。完成了它,工作得很好,但为了学习更多,我开始修改它

我更新了这个模型:

Todos.Todo = DS.Model.extend({
   title: DS.attr('string'),
   isCompleted: DS.attr('boolean'),
});

到此:

Todos.Todo = DS.Model.extend({
    title: DS.attr('string'),
    isCompleted: DS.attr('boolean'),
    date: DS.attr('date')
}); 

(我也在使用ember数据)。

添加到模板中,以便能够输入日期,然后将createTodo的控制器操作更新为:

actions: {
    createTodo: function(){
        var title = this.get('newTitle');
        var date = this.get('newDate');     
        if(!title.trim()){
            return;
        }
        var todo = this.store.createRecord('todo',{
            date: date,
            title: title,
            isCompleted: false              
        });
        //this clears the input field value
        this.set('newTitle', '');
        this.set('newDate', '');
        //and save the instance of the model.
        todo.save();
    },
//...More code

很好,一切正常,所以我使用本地存储适配器将其保存到localstorage

这就是事情发生的地方,日期没有保存到localstorage,这是因为适配器中使用的toJSONserialize方法。

具体来说,适配器是这样做的:

    _addRecordToNamespace: function (namespace, record) {
            var data = record.serialize({includeId: true});
            namespace.records[data.id] = data;
    }

它接受作为记录一部分的_data子对象,看起来是这样的:

//taken from the chrome inspector 
_data: Object
  __ember1386208719445_meta: Meta
  date: "12/11/2013"
  isCompleted: false
  title: "testing something"
  __proto__: Object

并返回:

Object {title: "testing something", isCompleted: false, date: null}

toJSON返回相同的内容。

SO TLDR&问题:

为什么方法toJSONserialize将我的date设置为null,而它显然有一个值,并且该值是一个字符串?

这是因为你说它的类型是date,但你把它设置为字符串,所以当ember数据试图序列化它时,它很困惑,因为它需要一个日期,所以它会返回null

serialize: function(date) {
  if (date instanceof Date) {
    var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var pad = function(num) {
      return num < 10 ? "0"+num : ""+num;
    };
    var utcYear = date.getUTCFullYear(),
      utcMonth = date.getUTCMonth(),
      utcDayOfMonth = date.getUTCDate(),
      utcDay = date.getUTCDay(),
      utcHours = date.getUTCHours(),
      utcMinutes = date.getUTCMinutes(),
      utcSeconds = date.getUTCSeconds();

    var dayOfWeek = days[utcDay];
    var dayOfMonth = pad(utcDayOfMonth);
    var month = months[utcMonth];
    return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " +
         pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT";
  } else {
    return null;
  }
}

您的日期格式无效。请尝试"2013-02-07T16:44:57"而不是"12/11/2013"。