Backbone.js视图中$ el和el之间有什么区别?

ali*_*sad 59 javascript backbone.js backbone-views

你能告诉Backbone.js视图$el和之间的区别el吗?

Ray*_*_on 80

让我们说你这样做

var myel = this.el; // here what you have is the html element, 
                    //you will be able to access(read/modify) the html 
                    //properties of this element,
Run Code Online (Sandbox Code Playgroud)

有了这个

var my$el = this.$el; // you will have the element but 
                      //with all of the functions that jQuery provides like,
                      //hide,show  etc, its the equivalent of $('#myel').show();
                      //$('#myel').hide(); so this.$el keeps a reference to your 
                      //element so you don't need to traverse the DOM to find the
                      // element every time you use it. with the performance benefits 
                      //that this implies.
Run Code Online (Sandbox Code Playgroud)

一个是html元素,另一个是元素的jQuery对象.

  • 不适合我,`这个.$ el('.class')`nets me $ el不是函数,我必须使用find:`this.$ el.find('.class')` (2认同)

Emi*_*ron 6

亩太短是完全正确的:

this.$el = $(this.el);
Run Code Online (Sandbox Code Playgroud)

并且很容易理解为什么,看一下视图的_setElement功能:

_setElement: function(el) {
  this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
  this.el = this.$el[0];
},
Run Code Online (Sandbox Code Playgroud)

这确保了el始终是DOM元素,并且它$el始终是它的jQuery对象.所以即使我使用jQuery对象作为el选项或属性,以下内容仍然有效:

// Passing a jQuery object as the `el` option.
var myView = new Backbone.View({ el: $('.selector') });
// Using a jQuery object as the `el` View class property
var MyView = Backbone.View.extend({
    el:  $('.selector')
});
Run Code Online (Sandbox Code Playgroud)

什么是缓存的jQuery对象?

它是一个保存在变量中的jQuery对象,用于重用.它避免了$(selector)每次使用类似的东西寻找元素的昂贵操作.

这是一个例子:

render: function() {
    this.$el.html(this.template(/* ...snip... */));
    // this is caching a jQuery object
    this.$myCachedObject = this.$('.selector');
},

onExampleEvent: function(e) {
    // Then it avoids $('.selector') here and on any sub-sequent "example" events.
    this.$myCachedObject.toggleClass('example');
}
Run Code Online (Sandbox Code Playgroud)

看到我写的更广泛的答案了解更多.