61

你能说出Backbone.js 视图$el之间的区别吗?el

4

4 回答 4

84

假设你这样做

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对象。

于 2013-05-20T16:07:54.427 回答
6

mu 太短是完全正确的:

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

而且很容易理解为什么,看看视图的_setElement功能

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

请参阅我写的广泛答案以了解更多信息。

于 2016-10-29T18:14:58.710 回答
2

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

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

于 2018-02-20T05:21:02.290 回答
1

现在回答这个问题已经太晚了,但是 --> this.$el是对 jQuery 上下文中元素的引用,通常用于诸如.html()or之类的东西.addClass()。例如,如果您有一个 id 为 someDiv 的 div,并且您将其设置为Backbone 视图的el属性,以下语句相同:

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

this.el是原生的 DOM 元素,jQuery 未触及。

于 2016-07-24T11:20:19.757 回答