在保存模型的同时,Backbone 1.2无效的Json Emiited?

时间:2015-06-30 11:25:02

标签: javascript json backbone.js

我是骨干的新手,我一直试图将我的模型保存到json文件中。

它工作正常,直到我尝试读取我的主干应用程序发出的json,并且Jsonlint我发现我的json无效。以下是一些细节:

我的模型(index.htm)

     //--------------
    // Model
    //--------------
    app.Todo = Backbone.Model.extend({
      defaults: {
        prenom:'',
        nom:'',
        adresse:'',
        profession:'',
        mail:'',
        cin:'',
        tel:''

  },

我的保存功能

   createTodoOnEnter: function(e){

    app.todoList.create(this.newAttributes());

    // clean input box
          prenom: this.prenom.val('');
          nom: this.nom.val('');
          adresse: this.adresse.val('');
          profession: this.profession.val('');
          mail: this.mail.val('');
          cin: this.cin.val('');
          tel: this.tel.val('');

  },
 newAttributes: function(){


    return {

      prenom: this.prenom.val().trim(),
      nom: this.nom.val().trim(),
      adresse: this.adresse.val().trim(),
      profession: this.profession.val().trim(),
      mail: this.mail.val().trim(),
      cin: this.cin.val().trim(),
      tel: this.tel.val().trim()

    }

  }

我在拯救时获得的json:

    {
    prenom: "ramy",
    nom: "dabbabi",
    adresse: "50 rue Fadhel ben achour",
    profession: "Developpeur",
    mail: "ramy@gmai.com",
    cin: 09008585,
    tel: 789456123
}

你可以注意到属性上没有双引号(prenom,nom ...),这就是我的json无效的原因。

我该如何解决?骨干中是否有任何功能允许我定义我的json格式?

我可以格式化this.model.create函数发送的json吗?

1 个答案:

答案 0 :(得分:0)

I'm guessing that you are calling the toJSON method, if you look at the docs you will see that it doesn't actually return a JSON string

Return a shallow copy of the model's attributes for JSON stringification. This can be used for persistence, serialization, or for augmentation before being sent to the server. The name of this method is a bit confusing, as it doesn't actually return a JSON string — but I'm afraid that it's the way that the JavaScript API for JSON.stringify works.

You can of course stringify the results of the call JSON.stringify (model.toJSON())

Additionally if necessary you can always override the backbone methods themselves.