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

时间:2013-05-20 09:34:44

标签: javascript backbone.js backbone-views

您能告诉Backbone.js视图中$elel之间的区别吗?

4 个答案:

答案 0 :(得分:79)

让我们说你这样做

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,

用这个

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.

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

答案 1 :(得分:6)

mu is too short完全正确:

this.$el = $(this.el);

很容易理解为什么,请看view's _setElement function

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

这确保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')
});

什么是缓存的jQuery对象?

这是一个分配给变量以供重用的jQuery对象。它避免了每次使用$(selector)之类的东西通过DOM查找元素的昂贵操作。

以下是一个例子:

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');
}

请参阅我写的extensive answer了解更多信息。

答案 2 :(得分:2)

简而言之,el允许您访问HTML DOM元素,即您可以引用和访问它们,而$ el是围绕el的jQuery包装器。

$ el不仅提供对特定DOM元素的访问,而且它充当jQuery选择器,并且您有权在特定DOM元素上使用jQuery库函数,如show(),hide()等。

答案 3 :(得分:1)

回答它已经太晚了但是 - > this.$el是jQuery上下文中元素的引用,通常用于.html().addClass()等内容。 例如,如果您有一个id为someDiv的div,并将其设置为Backbone视图的 el 属性,则以下语句是相同的:

this.$el.html() $("#someDiv").html() $(this.el).html()

this.el是本机DOM元素,不受jQuery的影响。