【问题标题】:What is the difference between $el and el in Backbone.js views?Backbone.js 视图中的 $el 和 el 有什么区别?
【发布时间】:2013-05-20 09:34:44
【问题描述】:

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

【问题讨论】:

标签: javascript backbone.js backbone-views


【解决方案1】:

假设你这样做

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

【讨论】:

  • 在 this.$el 上写查询是否有效?例如,编写 this.$el(".some-class") 以获取包含在视图 html 中的 .some-class 元素。
  • 不适合我,this.$el('.class') nets me $el 不是函数,我必须使用 find:this.$el.find('.class')
  • @JamesLock 你需要使用this.$('.class')。您将 jQuery 对象与 jQuery's core function 混淆了。 this.$el('.class')$('.selector')('.class') 一样,不是那样的。
【解决方案2】:

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 对象,分配给一个变量以供重用。它避免了每次通过 DOM 查找元素的代价高昂的操作,例如 $(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');
}

查看我写的extensive answer 以了解更多信息。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 这是在 jQuery 方面,问题是关于 backbone.js
    【解决方案4】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2018-03-17
      相关资源
      最近更新 更多