在backbone中定義的View類(見下面代碼)很是簡潔,給用戶提供了無限擴展的可能!View主要作了幾件事:react
一、關聯DOM 元素節點。View類爲backbone MVC中的視覺層確定會與DOM打交道!見構造函數中的_ensureElement方法,關聯DOM有兩種方式:若是實例化或擴展view類時設置了el屬性就會關聯頁面上的DOM,若是沒有,建立一個DOM元素默認爲div!app
二、事件代理。見方法 delegateEvents。這裏的事件代理指的是事件不是直接註冊在view對象上,而是對象屬相$el上,如backbone依賴的是jQuery的$el爲一個jQuery對象。ide
三、實例化VIew類時提供的一些便捷。見 var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];能夠在實例化是設置這些屬性,用於關聯model、collection,events用於設置代理事件…… 這樣就不經過擴展View類來作這些事!函數
四、還有混入backbone的Eventsthis
// Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... //backbone view 類 用於建立backbone view 對象 var View = Backbone.View = function(options) { this.cid = _.uniqueId('view');//建立cid options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. //初始化view時能夠設置這些屬性!!!!! var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. /** 設置view的el屬性和$el屬性!!! */ setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);//this.$el是jQuery對象,若是依賴的是jQuery的話! this.el = this.$el[0];//一個DOM元素節點 if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) {//註冊代理事件,所謂代理就是否是直接註冊在view 對象上 而是註冊在$el 中! if (!(events || (events = _.result(this, 'events')))) return this;//在擴展view類時能夠定義event屬性!!! this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]];//若是method不是函數,獲取對象中對應的方法! if (!method) continue;//跳出循環! var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this);//將method 綁定到this 如:method=this.method; eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() {//remove 代理的事件!!! this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. /*** 確保 有DOM 元素將view 渲染進裏面 ***/ _ensureElement: function() { //設置或建立view的element 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);//建立DOM元素,並設置元素的相關屬性! this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } });
以上爲backbone View的相關代碼,本身寫了點註釋,很差請指正!spa