Backbone源码研究 - Backbone.View

整个View的代码非常简洁,View构造逻辑也一目了然。

javascriptvar View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    options || (options = {});
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
};
  1. 生成唯一cid
  2. 合并参数列表
  3. 列表项目
  4. View的初始化
  5. 用户定义的初始化
  6. 事件处理

可以看到,最重要的代码,在于View的初始化。

javascript_ensureElement: function() {
    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);
    }
}

这段代码可以看出,如果实例化的时候有传入一个DOM节点,则绑定这个DOM节点,否则生成一个这样的DOM节点。

javascriptvar view = new View({
    el: $('body'),
    model: new Backbone.Model()
})

结语:嗯,Backbone.View真的好简单,没做什么事情。

你可能感兴趣的:(view,backbone,javascript)