Backbone源码分析(二)

简介:

  在传统MVC框架模式中,Model承担业务逻辑的任务。Backbone作为一个mvc框架,主要的业务逻辑交由Model与Collection来实现。Model代表领域对象,今天主要学一下Model源码中几个重要的函数。

  我们先看一下Model的构造函数做了哪些事情:


// Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    //对参数的处理
    var attrs = attributes || {};
    options || (options = {});

    this.cid = _.uniqueId(this.cidPrefix);//利用underscore生成一个客户端的唯一标识符cid
    this.attributes = {};//this.attributes是backbone中存放所有数据属性的对象
    //collection在获取model对应的后端url时使用,在model上设置collection并不会自动将model加入collection
    if (options.collection) this.collection = options.collection;
    //调用parse方法解析数据
    if (options.parse) attrs = this.parse(attrs, options) || {};
    //处理defaults默认数据,用attrs覆盖defaults
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    this.set(attrs, options);//接收attrs将数据处理后放入this.attributes
    this.changed = {};//changed属性用来保存修改过的属性数据,第一次set,不需要changed数据
    this.initialize.apply(this, arguments);//调用initialize初始化model,这个方法需要子类来覆盖
  };

  Model的构造函数主要做了以下几件事:

  • 处理参数
  • 处理model的属性:cid、attributes、collection
  • 解析数据、处理属性的默认值
  • set方法接收处理参数
  • 调用initialize做初始化操作

  

  接下来是一个重要的set函数,这个函数是Model最核心的一个方法


// Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {//{key: value}形式
        attrs = key;
        options = val;
      } else {// key, value, options形式
        (attrs = {})[key] = val;
      }

      options || (options = {});//设置options参数

      // Run validation.
      //首先验证参数,这里没有直接调用validate方法,而是调用_validate这个私有方法,该方法内部调用validate方法
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset      = options.unset;
      var silent     = options.silent;
      var changes    = [];//用来存放所有有变动的key
      var changing   = this._changing;//this._chaning用来标识set方法是否在处理中,我猜这里的设置跟webworker多线程有关
      this._changing = true;//这里代表属性的变动更新开始
      // this.changed = {};//不能放在这里,如果val没改变,所有changed都被清空掉了

      if (!changing) {//使用_previousAttributes来保留最近一次的attributes
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};//每次set时,changed都会被重置的{},这表示仅保留最近一次的变化
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev    = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {//遍历attrs
        val = attrs[attr];
        //对于单线程环境,current与_previousAttributes是一样的,这里的处理也应当是应对多线程
        if (!_.isEqual(current[attr], val)) changes.push(attr); //changes是本次变化的keys
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val; //存储变化量
        } else {
          delete changed[attr];
        }
        //这里根据unset的设置,如果unset为true移除,否则设置attributes中的对应属性
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      //idAttribute的目的是跟后端数据库记录的id保持一致
      if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

      // Trigger all relevant attribute changes.
      // 在所有赋值结束后,发送事件通知
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0; i < changes.length; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this; //这里我觉得也是跟多线程有关,如果多个线程同时更新model,最终只发出一个整体的change事件
      if (!silent) {
        while (this._pending) {//很奇怪的设置
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);//触发事件
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    }

  来整理一下set方法做的几件事:

  • 根据api的参数声明来处理参数
  • 声明几个与属性变化相关的变量
  • 设置_previousAttributes与changed来保存上次属性和这次的变化数据
  • 更新属性,保存本次变化数据和对应的key
  • 将发生变化的属性广播出去,change:key形式
  • 在model层次上发出change事件

  

  接下来是与后端打交道的save方法:


// Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    // save方法保持客户端与数据库内记录同步,前后端数据可能出现不一致情况,
    // 如果options中wait参数为true的话,会用后端返回的数据来更新前端数据
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {//`{key: value}`
        attrs = key;
        options = val;
      } else {//`"key", value`
        (attrs = {})[key] = val;
      }

      //在方法默认开启验证和解析
      options = _.extend({validate: true, parse: true}, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      // wait为false的话,首先在前端更新model,set中调用验证方法
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else if (!this._validate(attrs, options)) {//否则利用_validate进行验证
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;//保存this关键字
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;//这里先确保数据与为同步时保持一致
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        // wait属性为true,利用后端数据更新model的属性
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        // success带表更新成功后的回调函数。
        // save方法,将模型数据的同步完全封装起来,开发者只需专注于自身业务逻辑即可!
        if (success) success.call(options.context, model, resp, options);
        // 触发sync事件
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      //wait 为true,临时更新attributes,目的是下文中将model更新到数据库内
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      //根据model是否拥有idAttribute属性,决定是创建还是更新
      var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;//恢复数据,等到success后利用后端数据结果更新属性

      return xhr;
    },

其中用到的wrapError方法,源码如下:


// Wrap an optional error callback with a fallback error event.
  //将options中的error回调函数,变成一个能够触发error事件的回调函数
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  }

  save方法做的几件事:

  • 处理参数
  • 如果以客户端为准,则首先跟新model,否则验证需保存的属性
  • 声明局部变量,替换options中的success回调函数和error回调
  • 如果以后端返回数据为准,则先直接将attributes属性暂时更改,方便sync方法同步model,而后将attributes恢复,等待succes毁掉中利用后端返回结果更新

  

  接下来是销毁model的destroy方法:


// Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    //destroy方法用来销毁model,当wait属性为true时,等待后台销毁成功时做实际销毁工作
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();//移除其他代码中监听的model事件
        // 触发destroy事件
        model.trigger('destroy', model, model.collection, options);
      };

      // 后台销毁成功后的success回调
      options.success = function(resp) {
        if (wait) destroy();//销毁操作
        // 回调函数,业务逻辑相关
        if (success) success.call(options.context, model, resp, options);
        //拥有idAttribute属性,则触发sync事件
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {//数据库中并没有该条记录
        _.defer(options.success);//underscore函数,延迟调用function直到当前调用栈清空为止
      } else {
        wrapError(this, options);//包装错误
        xhr = this.sync('delete', this, options);// 与后台数据同步
      }
      if (!wait) destroy(); //无需后台等待的话,直接做销毁操作
      return xhr;
    }

  destroy方法做的事情:

  • 声明局部变量以及做销毁操作的destroy方法
  • 替换options中的success方法
  • 如果model未存储于数据库中,直接使用underscore的defer延迟执行success,否则向后台发送删除请求

 

  与验证相关的_validate方法如下:


// Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      //backbone希望在验证失败时候,validate方法返回一个error对象
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      //触发invalid事件,也就是说如果单独调用validate方法不会触发invalid事件
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

目录
相关文章
|
8天前
|
人工智能 自然语言处理 Shell
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
本教程指导用户在开源AI助手Clawdbot中集成阿里云百炼API,涵盖安装Clawdbot、获取百炼API Key、配置环境变量与模型参数、验证调用等完整流程,支持Qwen3-max thinking (Qwen3-Max-2026-01-23)/Qwen - Plus等主流模型,助力本地化智能自动化。
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
|
6天前
|
人工智能 JavaScript 应用服务中间件
零门槛部署本地AI助手:Windows系统Moltbot(Clawdbot)保姆级教程
Moltbot(原Clawdbot)是一款功能全面的智能体AI助手,不仅能通过聊天互动响应需求,还具备“动手”和“跑腿”能力——“手”可读写本地文件、执行代码、操控命令行,“脚”能联网搜索、访问网页并分析内容,“大脑”则可接入Qwen、OpenAI等云端API,或利用本地GPU运行模型。本教程专为Windows系统用户打造,从环境搭建到问题排查,详细拆解全流程,即使无技术基础也能顺利部署本地AI助理。
6483 13
|
4天前
|
人工智能 机器人 Linux
保姆级 OpenClaw (原 Clawdbot)飞书对接教程 手把手教你搭建 AI 助手
OpenClaw(原Clawdbot)是一款开源本地AI智能体,支持飞书等多平台对接。本教程手把手教你Linux下部署,实现数据私有、系统控制、网页浏览与代码编写,全程保姆级操作,240字内搞定专属AI助手搭建!
3726 11
保姆级 OpenClaw (原 Clawdbot)飞书对接教程 手把手教你搭建 AI 助手
|
4天前
|
存储 人工智能 机器人
OpenClaw是什么?阿里云OpenClaw(原Clawdbot/Moltbot)一键部署官方教程参考
OpenClaw是什么?OpenClaw(原Clawdbot/Moltbot)是一款实用的个人AI助理,能够24小时响应指令并执行任务,如处理文件、查询信息、自动化协同等。阿里云推出的OpenClaw一键部署方案,简化了复杂配置流程,用户无需专业技术储备,即可快速在轻量应用服务器上启用该服务,打造专属AI助理。本文将详细拆解部署全流程、进阶功能配置及常见问题解决方案,确保不改变原意且无营销表述。
4034 4
|
6天前
|
人工智能 JavaScript API
零门槛部署本地 AI 助手:Clawdbot/Meltbot 部署深度保姆级教程
Clawdbot(Moltbot)是一款智能体AI助手,具备“手”(读写文件、执行代码)、“脚”(联网搜索、分析网页)和“脑”(接入Qwen/OpenAI等API或本地GPU模型)。本指南详解Windows下从Node.js环境搭建、一键安装到Token配置的全流程,助你快速部署本地AI助理。(239字)
4161 21
|
12天前
|
人工智能 API 开发者
Claude Code 国内保姆级使用指南:实测 GLM-4.7 与 Claude Opus 4.5 全方案解
Claude Code是Anthropic推出的编程AI代理工具。2026年国内开发者可通过配置`ANTHROPIC_BASE_URL`实现本地化接入:①极速平替——用Qwen Code v0.5.0或GLM-4.7,毫秒响应,适合日常编码;②满血原版——经灵芽API中转调用Claude Opus 4.5,胜任复杂架构与深度推理。
7729 12
|
3天前
|
人工智能 安全 机器人
OpenClaw(原 Clawdbot)钉钉对接保姆级教程 手把手教你打造自己的 AI 助手
OpenClaw(原Clawdbot)是一款开源本地AI助手,支持钉钉、飞书等多平台接入。本教程手把手指导Linux下部署与钉钉机器人对接,涵盖环境配置、模型选择(如Qwen)、权限设置及调试,助你快速打造私有、安全、高权限的专属AI助理。(239字)
2414 5
OpenClaw(原 Clawdbot)钉钉对接保姆级教程 手把手教你打造自己的 AI 助手
|
4天前
|
人工智能 JavaScript API
零门槛部署本地AI助手:2026年Windows系统OpenClaw(原Clawdbot/Moltbot)保姆级教程
OpenClaw(原Clawdbot/Moltbot)是一款功能全面的智能体AI助手,不仅能通过聊天互动响应需求,还具备“动手”和“跑腿”能力——“手”可读写本地文件、执行代码、操控命令行,“脚”能联网搜索、访问网页并分析内容,“大脑”则可接入Qwen、OpenAI等云端API,或利用本地GPU运行模型。本教程专为Windows系统用户打造,从环境搭建到问题排查,详细拆解全流程,即使无技术基础也能顺利部署本地AI助理。
2890 5
|
6天前
|
人工智能 安全 Shell
在 Moltbot (Clawdbot) 里配置调用阿里云百炼 API 完整教程
Moltbot(原Clawdbot)是一款开源AI个人助手,支持通过自然语言控制设备、处理自动化任务,兼容Qwen、Claude、GPT等主流大语言模型。若需在Moltbot中调用阿里云百炼提供的模型能力(如通义千问3系列),需完成API配置、环境变量设置、配置文件编辑等步骤。本文将严格遵循原教程逻辑,用通俗易懂的语言拆解完整流程,涵盖前置条件、安装部署、API获取、配置验证等核心环节,确保不改变原意且无营销表述。
2353 6