Backbone.js - Given an element, how do I get the view?

后端 未结 5 1821
刺人心
刺人心 2020-12-15 03:33

I\'ve created a bunch of Backbone.js views. Each view has an associated element (view.el).

Given an element on the page — out of context of the view — w

5条回答
  •  情深已故
    2020-12-15 04:24

    I've been using a method inspired by Ed's solution but it does not require the use of jQuery. It does two things:

    1. It sets the attribute data-backbone-view on the root elements of all views. This is convenient when looking at the DOM tree in a debugger. You can immediately see which elements are associated with views. You can also use the CSS selector [data-backbone-view] to find elements that are the roots of Backbone views.

    2. It adds a backboneView property to each root element of a view. It is then possible to get from the DOM element to the view by looking a the DOM element's properties.

    I turn this on only when I'm debugging. Here is the code:

    var originalSetElement = Bb.View.prototype.setElement;
    
    Bb.View.prototype.setElement = function setElement(element) {
      if (this.el && this.el !== element) {
        delete this.el.backboneView;
      }
    
      element.backboneView = this;
      element.setAttribute("data-backbone-view", "true");
    
      return originalSetElement.apply(this, arguments);
    };
    

提交回复
热议问题