Backbone learning: backbone. localStorage. js

Source: Internet
Author: User

In the previous article, we used this file. Now let's simply analyze its mechanism. Let's just look at the comment and then OK:

/*** Backbone localStorage Adapter * Version 1.1.0 ** https://github.com/jeromegn/Backbone.localStorage */(function (root, factory) {if (typeof define = "function" & define. amd) {// AMD. register as an anonymous module. define (["underscore", "backbone"], function (_, Backbone) {// Use global variables if the locals are undefined. return factory (_ | root. _, Backbone | root. backbone) ;}) ;}e Lse {// RequireJS isn' t being used. assume underscore and backbone are loaded in <script> tags factory (_, Backbone) ;}( this, function (_, Backbone) {// A simple module to replace 'backbone. sync 'with * localStorage *-based // persistence. models are given GUIDS, and saved into a JSON object. simple // as that. // Hold reference to Underscore. js and Backbone. js in the closure in order // to make things Work even if they are removed from the global namespace // Generate four random hex digits. function S4 () {return (1 + Math. random () * 0x10000) | 0 ). toString (16 ). substring (1) ;}; // Generate a pseudo-GUID by concatenating random hexadecimal. // generate guidfunction guid () {return (S4 () + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + S4 () + S4 ());}; // Our Store is represented by a single JS object in * localStorage *. cr Eate it // with a meaningful name, like the name you 'd give a table. // window. store is deprectated, use Backbone. localStorage insteadBackbone. localStorage = window. store = function (name) {this. name = name; // the key value is stored in the key var store = this in localStorage. localStorage (). getItem (this. name); // obtain the data stored in localStorage. records = (store & store. split (",") | []; // All records are separated by commas };_. extend (Backbone. loca LStorage. prototype, {// Save the current state of the ** Store ** to * localStorage *. // (re) save all records save: function () {this. localStorage (). setItem (this. name, this. records. join (",") ;}, // Add a model, giving it a (hopefully)-unique GUID, if it doesn' t already // have an id of it's own. // create: function (model) {if (! Model. id) {model. id = guid (); model. set (model. idAttribute, model. id);} this. localStorage (). setItem (this. name + "-" + model. id, JSON. stringify (model); this. records. push (model. id. toString (); this. save (); return this. find (model) ;}, // Update a model by replacing its copy in 'this. data '. // update: function (model) {this. localStorage (). setItem (this. name + "-" + model. id, JSON. stringify (model); if (! _. Include (this. records, model. id. toString () this. records. push (model. id. toString (); this. save (); return this. find (model) ;}, // Retrieve a model from 'this. data 'by id. // find data find: function (model) {return this based on the model id. jsonData (this. localStorage (). getItem (this. name + "-" + model. id) ;}, // Return the array of all models currently in storage. // obtain all data findAll: function () {return _ (this. recor Ds ). chain (). map (function (id) {return this. jsonData (this. localStorage (). getItem (this. name + "-" + id) ;}, this ). compact (). value () ;}, // Delete a model from 'this. data', returning it. // delete a data record. destroy: function (model) {if (model. isNew () return false this. localStorage (). removeItem (this. name + "-" + model. id); this. records = _. reject (this. records, function (id) {return id = model. id. toString () ;}); t His. save (); return model;}, localStorage: function () {return localStorage;}, // fix for "illegal access" error on Android when JSON. parse is passed null jsonData: function (data) {return data & JSON. parse (data) ;}}); // localSync delegate to the model or collection's // * localStorage * property, which shocould be an instance of 'store '. // window. store. sync and Backbone. localSync is deprectated, us E Backbone. localStorage. sync instead // encapsulate the local analog interface Backbone. localStorage. sync = window. store. sync = Backbone. localSync = function (method, model, options) {// The localStorage parameter in the model or the localStorage parameter in the collection. // It is a Store instantiated object var store = model. localStorage | model. collection. localStorage; var resp, errorMessage, syncDfd = $. deferred & $. deferred (); // If $ is having Deferred-use it. try {switch (Method) {// process different request methods: read (GET) create (POST) update (PUT) delete (DELETE) case "read": resp = model. id! = Undefined? Store. find (model): store. findAll (); break; case "create": resp = store. create (model); break; case "update": resp = store. update (model); break; case "delete": resp = store. destroy (model); break;} catch (error) {if (error. code = DOMException. QUOTA_EXCEEDED_ERR & window. localStorage. length = 0) errorMessage = "Private browsing is unsupported"; else errorMessage = error. message;} if (resp ){ Model. trigger ("sync", model, resp, options); // execute the callback if (options & options. success) options. success (resp); if (syncDfd) syncDfd. resolve (resp);} else {errorMessage = errorMessage? ErrorMessage: "Record Not Found"; if (options & options. error) options. error (errorMessage); if (syncDfd) syncDfd. reject (errorMessage);} // add compatibility with $. ajax // always execute callback for success and error if (options & options. complete) options. complete (resp); return syncDfd & syncDfd. promise () ;}; Backbone. ajaxSync = Backbone. sync; Backbone. getSyncMethod = function (model) {if (model. localStorage | (model. collection & model. collection. localStorage) {return Backbone. localSync;} return Backbone. ajaxSync;}; // Override 'backbone. sync 'to default to localSync, // the original' Backbone. sync 'is still available in' Backbone. ajaxSync '// rewrite the Backbone sync function, so that the default request of the program can be forwarded to the Store to process the Backbone. sync = function (method, model, options) {return Backbone. getSyncMethod (model ). apply (this, [method, model, options]) ;}; return Backbone. localStorage ;}));

Welcome to the guidance and suggestions.

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.