[Backbone] Parse not formatted JSON code

本文讨论了如何修复并优化Appointment模型中JSON解析错误,包括修改parse函数以正确处理JSON格式,纠正拼写错误,调整id属性,并更新JSON序列化方式以匹配服务器期望的格式。

The good Dr. recently had another team implement the server and they slightly messed up the format of the JSON returned for Appointment data. Instead of returning JSON like { "title": "Ms. Kitty Hairball Treatment", "cancelled": false, "id": 1 } the server is returning JSON like { "appointment": { "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }

Add to the parse function below code to handle return the JSON without the "appointment" as root.

var Appointment = Backbone.Model.extend({
  parse: function(response){
    return response.appointment;
  }
});

Great! Now let's take care of that pesky spelling error.

Change 'cankelled' to 'cancelled' and make sure to remove the 'cankelled' property.

Make sure to refer to the JSON below and to the right.

var Appointment = Backbone.Model.extend({
  parse: function(response){
    response = response.appointment;
    response.cancelled = response.cankelled;
    delete response.cankelled;
    return response;
  }
});

update the Appointment model to use the"identifier" string as the idAttribute instead of the default "id", that way you can call appointment.idlater on. 

var Appointment = Backbone.Model.extend({
  idAttribute: 'identifier',
  parse: function(response){
    var appointment = response.appointment;
    appointment.cancelled = appointment.cankelled;
    delete appointment.cankelled;
    return appointment;
  }
});

In the Appointment instantiation code below, make sure the attributes get run through our new parse function by passing in the appropriate option to the Appointment constructor

var appointment = new Appointment(data, {parse: true}); //Forse to pasre the data

He just tried to create a new Appointment and it crashed the server because the JSON sent up to represent the Appointment was in the wrong format. Update toJSON below to return the JSON the server expects. (Make sure you don't modify the model.attributes object)

var Appointment = Backbone.Model.extend({
  toJSON: function(){
    var attrs = _.clone(this.attributes);
    attrs.cankelled = attrs.cancelled;
    delete attrs.cancelled;
    return { appointment: attrs};
  }
});

Now that we've modified toJSON to return mangled JSON, we need to change our AppointmentView to useattributes instead of toJSON.

var AppointmentView = Backbone.View.extend({
  template: _.template('<span>' +
                        '<%= title %></span>' +
                        '<a href="#">x</a>'),

  render: function(){
    this.$el.html(this.template(this.model.attributes));
  }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值