Backbone.View.extend之后的构造函数实例化经历了一些什么处理

首先看Backbone.View的构造函数源码:

var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view'); // 为需要的客户端模型或DOM元素生成一个全局唯一的id。如果prefix参数存在, id 将附加给它。就是生成_id属性 值是唯一的。
    options || (options = {});
    _.extend(this, _.pick(options, viewOptions));//这里挑选options下面的参数赋给构造函数的prototype对象
    this._ensureElement();// 看下面的_ensureElement
    this.initialize.apply(this, arguments);  执行我们写的initialize函数了
    this.delegateEvents();//绑定我们events json中的事件
  };
_ensureElement: function() { //这里主要做的就是创建了一个View层的容器,即$el  并赋予attributes属性和class name
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
// Cached regex to split keys for `delegate`.

var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties.

var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

 

posted @ 2017-02-26 12:05  iwang5566  阅读(843)  评论(0编辑  收藏  举报