Meet Backbone (ii)

Source: Internet
Author: User

  Backbone.model (model)

Models (model) is at the heart of any JavaScript application, including data interactions and a wealth of logic associated with them: transformations, validations, computed properties, and access control. Model in backbone is the most basic and fundamental data base class for data models.

  Create a Model object

  Extend Backbone.Model.extend(properties, [classProperties])

var world = Backbone.Model.extend ({     initialize:function () {        console.log (' created a Model object ')     }}); New World ()

Set and Get Properties (data)

  Get model.get(attribute) Gets the current property (attributes) value from the current model.

  Set model.set(attributes, [options]) Set one or more hash attributes (attributes) to the model. If any of the properties change the state of the model, the "change" event is triggered when the {silent:true} option parameter is not passed in, and the event that changes a particular property is also triggered.

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    },    initialize:function () {        Console.log (' created a Model object ')    }}); var world = New World () Console.log ("World.get")//10world.set ({' age ':] Console.log (World.get (' age '))//50

  Custom Methods

var world = Backbone.Model.extend ({    defaults: {        text: ' Hello, world! '    },    say:function () {        Console.log (This.get (' text '))    }); var world = New World () World.say ()//hello, world!

  listen for changes in property values  

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    },    initialize:function () {        this.on (' Change:name ', function (model,value) {            var oldname = model.previous (' name ');            Console.log (' original name is: ' + oldname + ', now the name is: ' + value ')}})    ; var world = New World () world.set ({' name ': ' CCX '})/ /The original name is: lbs, now the name is: CCX

  Data Validation

Validate model.validate(attributes, options)

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    },    initialize:function () {        this.on (' invalid ', function (model,error) {            console.log (error);        });    },    validate:function ( Attrs) {        if (!_.isstring (attrs.name)) return ' name must be a string ';        if (!_.isnumber (attrs.age)) return ' age must be a number ';    }}); var world = New World ()//According to the validation rule (v1.0.0) {validate:true} world.set ({name: ' CCX ', Age: ' Three '},{validate:true})//ages must be numbers

When the set method is called, set Validate to True, turn on data validation , do not set validate to True , or set silent to trueto turn off data validation.

  Delete attribute (data)

  unset model.unset(attribute, [options]) Removes the specified attribute (attribute) from the Internal property hash list. If the silent option is not set, the "change" event is triggered.

  Clear model.clear([options]) Removes all attributes from the model, including the ID attribute. If the silent option is not set, the "change" event is triggered.

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    }}); World.unset (' name ') Console.log (world.get (' name '))  //undefinedworld.set ({name: ' CCX '}) Console.log (World.get ( ' Name ')//ccxconsole.log (World.get (' age '))//10world.clear () Console.log (world.get (' name '))  // Undefinedconsole.log (World.get (' age '))  //undefined

Property Manipulation

  attributes model.attributes The Attributes property is an internal hash list that contains the state of the model (the properties of the instantiated model object are persisted in the Attributes Property object).

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    }}); Console.log (world.attributes)//Object {name: "lbs", age:10}

previous model.previous(attribute) This method can be used to get the old value of a changed property during the "change" event.

previousattributes model.previousAttributes() Returns a copy of the previous property of the model. Typically used to get the difference between different versions of a model, or to roll back the model state when an error occurs.

var world = Backbone.Model.extend ({    defaults: {        Name: ' lbs ',        age:10    }}) var world = New World () World.on ( ' Change:name ', function (model,value) {    var oldname = model.previous (' name ');    var newname = model.get (' name ');    Console.log (' original name is: ' + oldname + ', now the name is: ' + newname);}) World.on (' Change:age ', function (model,value) {    var attrs = Model.previousattributes ();    var oldage = attrs.age;    Console.log (' original Age is: ' + Oldage + ', now the Age is: ' + value ')}) World.set ({name: ' CCX '})//The original name is: lbs, now the name is: Ccxworld.set ({ages: 50})//The original Age is: 10, the current age is: 50

Synchronizing Data

Save model.save([attributes], [options]) By delegating to Backbone.sync, save the model to the database (send client data to the server to save)

var world = Backbone.Model.extend ({    URL: ' backbone-test.php ',    defaults: {        Name: ' lbs ',        age:10    }} var world = New World () World.set ({name: ' CCX ', age:50})//world.save () world.save (null,{    success:function (model, Response) {        console.log (response.code)    }})//php file//Set the format of the received Data header (' Content-type:application/json; Charset=utf-8 '); Gets the data sent by the client   $data = Json_decode (file_get_contents ("Php://input"));/* Gets the value of each property and saves it to the server *///returns the update successful flag die (Json_ Encode (Array (' Code ' = ' 0 '));

Fetch model.fetch([options]) Resetting the state of the model from the server by delegating to Backbone.sync (get Server data)

var world = Backbone.Model.extend ({    URL: ' backbone-test.php ',    defaults: {        Name: ' lbs ',        age:10    }} var world = New World () World.fetch ({    success:function (model,response) {        console.log (World.tojson ())// Object {name: "CCX", Age:20, Code:1}    },    error:function (Error) {        Console.log (Error)}    })//php file $json = Array (' name ' = ' ccx ', ' age ' =>20, ' Code ' =>1);  echo Json_encode ($json);

Destroy model.destroy([options]) Save the model to the database by delegating to Backbone.sync

When the Destroy method is called, the object's ID data is sent to the server as a delete request, the server receives the data, deletes the corresponding data record, and sends a flag to the client for deletion success.

var world = Backbone.Model.extend ({    URL: ' backbone-test.php ',    defaults: {        Name: ' lbs ',        age:10    },    idattribute: ' Code '}) var world = New World ({    ' code ': +}) World.destroy ({    success:function (model,response) {        if (response.code = = ' 0 ') {             console.log (model.get (' code ') + ' data deleted ')  //110 data deleted         }    },    error:function (Error) {        Console.log (Error)    },    wait:true})//php file echo json_encode (Array (' Code ' =>0));

Meet Backbone (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.