我想建立一个像对象/类的Backbone.Model。

我浏览了Backbone文档,发现他们通过两个步骤创建了一个具有可继承属性,方法的可继承对象/类:

一,创建具有某些属性的函数

var Model = Backbone.Model = function(attributes, options) {
    var defaults;
    attributes || (attributes = {}); //?
    if (options && options.parse) attributes = this.parse(attributes); //?
    if (defaults = getValue(this, 'defaults')) {
      attributes = _.extend({}, defaults, attributes); // ?
    }
    if (options && options.collection) this.collection = options.collection;
    this.attributes = {};
    this._escapedAttributes = {};
    this.cid = _.uniqueId('c');
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this.set(attributes, {silent: true});

    this.changed = {};
    this._silent = {};
    this._pending = {};
    this._previousAttributes = _.clone(this.attributes);
    this.initialize.apply(this, arguments);
};


二。使用下划线的扩展为其提供一些功能

_.extend(Model.prototype, Events, { // Events?
   changed: null,

   _silent: null,

   _pending: null,

   idAttribute: 'id',

   initialize: function(){},

   toJSON: function(options) {
       return _.clone(this.attributes);
   }

   // other Model methods...
};


我对此行为有一些疑问:


第一部分的3-4行做什么
第6行会发生什么?
为什么我们过分“ _.extend”事件对象,我还能给参数什么呢?


还有什么我需要注意的吗?

问候

最佳答案

第3行attributes || (attributes = {});short circuit evaluation的示例。
如果attribute具有虚假的valye,则javascript将评估OR表达式的第二部分。该部分为attributes分配一个值为{}的空对象。最终结果是,如果属性为null或未定义(典型情况),则为属性分配一个空对象。

那行相当于说:

if (attributes == false) { // attributes can be any value that evaluates to false
                           // attributes could be null, undefined, false, 0 etc
   attributes = {};
}


与第4行相同,if (options && options.parse) attributes = this.parse(attributes);

如果options对象存在,即它不是null或未定义,并且options对象具有一个称为parse的有效属性,则为属性分配this.parse(attributes)的值;

编辑1:

_.extend行可由Underscore.js documentation解释。

它是创建新对象的标准模式,该对象将包含所有传入对象的属性。在第一个示例attributes = _.extend({}, defaults, attributes); // ?中,该模式用于覆盖可能传递的默认值。您会在大多数允许您传递options对象的插件中看到这种模式。如果您不输入任何内容,将使用默认值。如果仅传递一些属性,则其余的将从默认值中获取其值。

http://api.jquery.com/jQuery.extend/不是一回事。但是它非常相似。他们的文档要好得多。您将更好地理解该概念。

编辑2:

Backbone Events类具有一些与事件处理相关的方法。 Backbone Model类还需要能够利用事件处理。它需要引发事件以告诉视图重新渲染自身,当视图更改基础数据时,它需要侦听来自dom的事件。定义Model类时,可以从头开始重写此事件处理功能,或者可以扩展Model类以从Events类中获取这些方法。后者正在发生。

如果阅读$ .extend或_.extend的文档,您将认识到Model类不仅可以使用Events下的属性进行扩展,还可以使用其他属性(例如toJSON和initialize等)进行扩展。

关于javascript - 如何使用下划线创建自己的可继承类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11467108/

10-12 13:23