1
votes

I am still new to backbone:

Here is my problem that I find hard to explain:

on initialisation there is a model something like this:

Model:
 {
  Id:xxx,
  Questions:
           [ 
             {
              Id: "yy", 
              Selections: 
                        [ 
                         {OptionId:"aaa"},
                         ...,
                         {OptionId:"zzz"} 
                        ]
             }, 
           ....
           ]
 } 

there is a event method updates Selections Collection. After event triggers I got two different result by with two code below:

window.pkg.Questions.get(this.Id).Selections.reset(selectedoptions);

console.log(window.pkg.Questions.get(this.Id).Selections.toJSON());        
console.log(window.pkg.Questions.get(this.Id).toJSON().Selections);

The first log shows the updated model, however the later shows initial default value.

why it is working like this?

enter image description here

1

1 Answers

0
votes

They are two different copies. Your QuestionModel has a SelectionsCollection property called Selections, and a Backbone attribute, also called Selections. I assume you want to use the SelectionsCollection, and the attribute will not stay in sync with that. The attribute is the original json which I assume was inadvertently added to the model.

Hard to say exactly how to fix it, because you did not show the code where you create and fetch these models and collections. Wherever you take the Selections JSON and and initially reset it into the collection, you can remove it from the JSON and/or unset it on the QuestionModel if it is already there....

This would also print the wrong, original data:

console.log(window.pkg.Questions.get(this.Id).get('Selections')); // print original JSON

You can remove it in QuestionModel's parse:

parse: function(data) {
    // removing Selections from data here will prevent
    // it from being added as an attribute.
    delete data.Selections; 
    return data;
}

If you do this, and you want the Selections to be included in the toJSON output of QuestionModel, you would also need to override toJSON.

toJSON: function() {
    // get json for Question
    var json = Backbone.Model.prototype.toJSON.call(this);
    // add updated json for selections
    json.Selections = this.Selections.toJSON();

    return json;
}