0

我一直在搞乱ember.js todoMVC示例。完成并工作得很好,但为了了解更多信息,我开始修改它。

我从这里更新了模型:

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-data)。

添加到模板中以便能够输入日期,然后将控制器操作更新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 adapter

这是事情中断的地方,日期没有保存到localstorage,这是因为适配器中使用了toJSONandserialize方法。

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

    _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返回相同的东西。

所以 TLDR && 问题:

为什么这些方法toJSONserialize我的设置date为null,当它显然有一个值,并且那个值是一个字符串?

4

2 回答 2

1

这是因为您说它是 date 类型,但是您将其设置为字符串,所以当 ember data 尝试对其进行序列化时,它会感到困惑,因为它需要一个日期,所以它会返回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-12-05T03:32:45.510 回答
-1

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

于 2013-12-05T02:40:09.100 回答