The use of backbone development also has a period of time, until the first 2 weeks, only to find that the previous walk is a detour, the use of the way is wrong.
It's not a rip. Keep track of what you need to be aware of when you use backbone's defaults today.
As backbone knows, defaults can save a lot of repetitive initialization code snippets.
1 var Model = Backbone.Model.extend ({2 defaults: {3 str: ' This is String ', 4 num:05 }6}); 7 8 var a=New Model (); 9 var b=New Model ();
Then try the following code
1 varModel =Backbone.Model.extend ({2 defaults: {3 list: [],4 obj: {}5 }6 });7 8 varA =NewModel ();9 varb =NewModel ();Ten OneA.get (' list '). Push (1); AA.get (' obj ') [' str '] = ' tihs is String '; - -Console.log ("B.attributes", b.attributes);
The results are as follows
Yes, the data for Model B is also changed for simple reasons: Array and object are reference types.
There are 2 solutions:
1, when initializing an object, explicitly passing in the initialized data
1 var New Model ({list: [], obj: {}}); 2 var New Model ({list: [], obj: {}});
2, modify the value of the Defaults object, return by function
1 var Model = Backbone.Model.extend ({2 function () {3 return {4 list: [],5 obj: {}6 }; 7 }8 });
Look at the model method of backbone
1 varModel = Backbone.model =function(attributes, options) {2 varattrs = Attributes | | {};3Options | | (options = {});4 This. CID = _.uniqueid (' C ');5 This. attributes = {};6 if(options.collection) This. Collection =options.collection;7 if(options.parse) Attrs = This. Parse (attrs, options) | | {};8Attrs = _.defaults ({}, Attrs, _.result ( This, ' defaults '));9 This. Set (attrs, options);Ten This. changed = {}; One This. initialize.apply ( This, arguments); A};
The focus is: Attrs = _.defaults ({}, Attrs, _.result (this, ' defaults '));
One of the underscore methods _.result
Just remind yourself: do not look at the document on the line, regardless of the source code. Really can't be lazy again!
Talking about the defaults of backbone