Models in backbonejs (1)
I. Model and attribute model are the cornerstones of MVC applications. They are responsible for storing the data required by applications, verifying data, implementing access control, and implementing specific business logic required by applications. Backbone defines a Model by extending the Backbone. Model object. For example, var Mymodel = Backbone. Model. extend ({...}); we do not need to define a data structure within the Model. backbone supports dynamic definition during Model initialization. For example, mymodeltest = new Mymodel ({date: '1970-08-14 ', name: 'job', description: 'test'}); 1: Model copying newmodel = mymodeltest. clone (); obtain an independent copy of the model. Modifications to the mymodeltest model instance are not reflected in newmodel. If a value is assigned to another object, it is reflected in another object. 2: Set the default property value, for example, var _ model = Backbone. model. extend ({defaults: {date: '', name: 'job', description:'', gender: 'women'}) var aaa = new _ model ({description: 'testtest'}); aaa. get ('date ')! = Undefine // true aaa. get ('name') // joan aaa. get ('description') // testtest 3: You can use a function to set the default property value, for example, var _ model = Backbone. model. extend ({defaults: {name: 'job', description: '', gender: 'women', date: function () {var date = new Date (); return date. toISOString () ;}}) 4: after the model object is created, the initialize () method, the initialize method is called immediately to initialize the value of the model object. You can also set initialize: function () {if (! This. has ('date') {var date = new date (); this. set ('date', date. isISOString () ;}} uses the has method to determine whether the date attribute has not been initialized before. To avoid overwriting it, use the set method to set the default date attribute 2: some special methods for operating model attributes 1: get (): get attribute value 2: set (): update or create a single attribute value. multiple attributes can be updated at a time, the format of 'key-value' is as follows: aaa. set ({name: 'saly', gender: 'man'}) If the property does not exist, the property is automatically created. If the setting is successful, true is returned, indicating a reference to an available model. Otherwise, false. 3: unset (): deletes an attribute from the model. For example, aaa. unset ('description') 4: clear (): deletes all attributes from the model. 5: has (): Check whether a certain attribute exists in the model. If yes, true is returned, for example, aaa. has ('name'), // true