Backbone的localStorage.js源码详细分析

Backbone.localStorage.js是将数据存储到游览器客户端本地的(当没有服务器的情况下)

地址:https://github.com/jeromegn/Backbone.localStorage

1     整个函数是一个自执行函数,简化版形式如下

(function(a,fn) {

//...

})(a,fn);

2     9-12行/**---------此处是判断上下文有没有引入AMD模块(如requirejs)-----------*/

if(typeofdefine==="function"&&define.amd) {

// AMD. Register as an anonymous module.

define(["underscore","backbone"],function(_, Backbone) {

// Use global variables if the locals are undefined.

returnfactory(_ || root._, Backbone || root.Backbone);

});

}else{

// RequireJS isn‘t being used. Assume underscore and backbone are loaded in script tags

factory(_,Backbone);

}

此种判断方法比较常见,类似的如 toastr.js种

typeofdefine===‘function‘&&define.amd?define:function(deps, factory) {

if(typeofmodule!==‘undefined‘&&module.exports) {//Node

module.exports= factory(require(‘jquery‘));

}else{

window[‘toastr‘] = factory(window[‘jQuery‘]);

}

}

/**
 * Backbone localStorage Adapter
 * Version 1.1.0
 *
 * https://github.com/jeromegn/Backbone.localStorage
 */
(function (root, factory) {

  /**---------此处是判断上下文有没有引入AMD模块(如requirejs)-----------*/
   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);
      });
   } else {
      // 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.
// /**---------此处生成随机数  如 d9ab5797-9773-9bcd-27b1-9f23a3170957-----------*/
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

// Our Store is represented by a single JS object in *localStorage*. Create it
// with a meaningful name, like the name you‘d give a table.
// window.Store is deprecated, use Backbone.LocalStorage instead
  /**---------定义LocalStorage函数-----------*/
Backbone.LocalStorage = window.Store = function(name) {
  this.name = name;
  var store = this.localStorage().getItem(this.name);
  this.records = (store && store.split(",")) || [];
};
  /**---------扩展LocalStorage函数 的 增删改查 等其他方法-----------*/
_.extend(Backbone.LocalStorage.prototype, {

  // Save the current state of the **Store** to *localStorage*.
  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();//生成唯一id
      model.set(model.idAttribute, model.id);//给模型添加一条新属性id
    }
    this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));//setItem为原生localstorage的方法,此处是真正的把数据存储到客户端
    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: function(model) {
    return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id));
  },

  // Return the array of all models currently in storage.
  findAll: function() {
    return _(this.records).chain()
      .map(function(id){
        return this.jsonData(this.localStorage().getItem(this.name+"-"+id));
      }, this)
      .compact()
      .value();
  },

  // Delete a model from `this.data`, returning it.
  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();
    });
    this.save();
    return model;
  },

  localStorage: function() {
    return localStorage;//返回原生的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 should be an instance of `Store`.
// window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
  var store = model.localStorage || model.collection.localStorage;

  var resp, errorMessage, syncDfd = $.Deferred && $.Deferred(); //If $ is having Deferred - use it.//生成query的Deferred对象
  //此处是一个较大的知识点,就是promise规范,和jquery的deferred 和promise 此处不展开

  try {

    switch (method) {
      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);
    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();
};
  /**---------保存原来的sync-----------*/
Backbone.ajaxSync = Backbone.sync;

  /**---------此处来判断返回哪个函数,用localstorage还是发送ajax-----------*/
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‘
  /**---------覆盖Backbone的sync,因为原来的已经保存-----------*/
Backbone.sync = function(method, model, options) {
  return Backbone.getSyncMethod(model).apply(this, [method, model, options]);
  //注意:Backbone.getSyncMethod(model)返回的是一个函数,再apply(),才执行返回的这个函数
};

return Backbone.LocalStorage;
}));
时间: 2024-12-26 22:03:36

Backbone的localStorage.js源码详细分析的相关文章

OpenStack_Swift源码分析——创建Ring及添加设备源码详细分析

1 创建Ring 代码详细分析 在OpenStack_Swift--Ring组织架构中我们详细分析了Ring的具体工作过程,下面就Ring中增加设备,删除设备,已经重新平衡的实现过程作详细的介绍. 首先看RingBuilder类 def __init__(self, part_power, replicas, min_part_hours): #why 最大 2**32 if part_power > 32: raise ValueError("part_power must be at

ConcurrentHashMap 源码详细分析(JDK1.8)

ConcurrentHashMap 源码详细分析(JDK1.8) 1. 概述 <HashMap 源码详细分析(JDK1.8)>:https://segmentfault.com/a/1190000012926722 Java7 整个 ConcurrentHashMap 是一个 Segment 数组,Segment 通过继承 ReentrantLock 来进行加锁,所以每次需要加锁的操作锁住的是一个 segment,这样只要保证每个 Segment 是线程安全的,也就实现了全局的线程安全.所以很

fastclick.js源码解读分析

阅读优秀的js插件和库源码,可以加深我们对web开发的理解和提高js能力,本人能力有限,只能粗略读懂一些小型插件,这里带来对fastclick源码的解读,望各位大神不吝指教~! fastclick诞生背景与使用 在解读源码前,还是简单介绍下fastclick: 诞生背景 我们都知道,在移动端页面开发上,会出现一个问题,click事件会有300ms的延迟,这让用户感觉很不爽,感觉像是网页卡顿了一样,实际上,这是浏览器为了更好的判断用户的双击行为,移动浏览器都支持双击缩放或双击滚动的操作,比如一个链

DownloadProvider 源码详细分析

DownloadProvider 简介 DownloadProvider 是Android提供的DownloadManager的增强版,亮点是支持断点下载,提供了“开始下载”,“暂停下载”,“重新下载”,“删除下载”接口.源码下载地址 DownloadProvider 详细分析 DownloadProvider开始下载的是由DownloadManager 的 enqueue方法启动的,启动一个新的下载任务的时序图  开始新的下载时候会调用DownloadManager的enqueue方法,然后再

android_launcher的源码详细分析

转载请注明出处:http://blog.csdn.net/fzh0803/archive/2011/03/26/6279995.aspx 去年做了launcher相关的工作,看了很长时间.很多人都在修改launcher,但还没有详细的文档,把自己积累的东西分享出来,大家一起积累.这份源码是基于2.1的launcher2,以后版本虽有变化,但大概的原理一直还是保留了. 一.主要文件和类 1.Launcher.java:launcher中主要的activity. 2.DragLayer.java:l

RWTHLM 源码详细分析(三)

现在是第三篇,后面的顺序是从输出层,到隐层,然后到输入层的顺序来写,最后在写一下整个框架.这篇介绍输出层的实现,整个程序非常关键的是矩阵相乘的函数,所以在看整个输出层实现之前,非常有必要详细的介绍一下里面反复用到的矩阵相乘函数的各个参数的含义.先看一下FastMatrixMatrixMultiply这个函数,如下: inline void FastMatrixMatrixMultiply( const float alpha, const float a[], const bool transp

HashMap 源码详细解析 (JDK1.8)

概要 HashMap 最早出现在 JDK 1.2 中,底层基于散列算法实现.HashMap 允许 null 键和 null 值,在计算哈键的哈希值时,null 键哈希值为 0.HashMap 并不保证键值对的顺序,这意味着在进行某些操作后,键值对的顺序可能会发生变化.另外,需要注意的是,HashMap 是非线程安全类,在多线程环境下可能会存在问题. HashMap 底层是基于散列算法实现,散列算法分为散列再探测和拉链式.HashMap 则使用了拉链式的散列算法,并在 JDK 1.8 中引入了红黑

jqueryui.position.js源码分析

最近要写前端组件了,狂砍各种组件源码,这里分析一款jqueryui中的posistion插件,注意,它不是jqueryui widget,首先看下源码总体结构图 1.看到$.fn.position 是不是很熟悉?嗯,就是将position方法挂载到原型上,然后控件就可以直接调用了, 2.$.ui.position 这个对象是,用来进行冲突判断的,什么冲突?就是元素与父容器所拥有的空间以及当前可用窗口的控件,默认情形下,如果冲突则采用反转方向的方式显示:对这一点不要惊讶,一切都是为了正常显示而用的

MyVoix2.0.js 源码分析 WebSpeech与WebAudio篇

楔 子 随着移动互联网时代的开启,各种移动设备走进了我们的生活.无论是日常生活中人手一部的手机,还是夜跑者必备的各种智能腕带,亦或者是充满未来科技感的google glass云云,它们正渐渐改变着我们的生活习惯以及用户交互习惯.触摸屏取代了实体按键,Siri开始慢慢释放我们的双手,而leap motion之类的硬件更是让我们彻底不需要接触IT设备便能通过手势控制它们.在这样的大背景下,前端的交互将涉及越来越多元的交叉学科,我们正如十几年前人们经历Css的诞生一样,见证着一场带动整个行业乃至社会的