整個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