// Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... varView = Backbone.View = function (options) { this.cid = _.uniqueId('view'); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); };
// 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. _ensureElement: function () { if (!this.el) { // ... // omit this because we pass 'el' as options to the View. // ... } else { this.setElement(_.result(this, 'el')); } }
// Change the view's element (`this.el` property) and re-delegate the // view's events on the new element. setElement: function (element) { this.undelegateEvents(); this._setElement(element); this.delegateEvents(); returnthis; }
// Creates the `this.el` and `this.$el` references for this view using the // given `el`. `el` can be a CSS selector or an HTML string, a jQuery // context or an element. Subclasses can override this to utilize an // alternative DOM manipulation API and are only required to set the // `this.el` property. _setElement: function (el) { this.$el = el instanceofBackbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; }
// Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function () { this._removeElement(); this.stopListening(); returnthis; },
// Remove this view's element from the document and all event listeners // attached to it. Exposed for subclasses using an alternative DOM // manipulation API. _removeElement: function () { this.$el.remove(); }
解除事件监听,删掉元素。
最终的 hide 方法
于是,我模仿着写了一个 hide 方法:
1 2 3 4 5
hide: function () { this.undelegateEvents(); this.$el.empty(); this.stopListening(); }