整个View的代码很是简洁,View构造逻辑也一目了然。javascript
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(); };
能够看到,最重要的代码,在于View的初始化。java
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节点。app
javascriptvar view = new View({ el: $('body'), model: new Backbone.Model() })
结语:嗯,Backbone.View真的好简单,没作什么事情。this