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

问题描述 投票:58回答:4

你能否在Backbone.js视图中告诉$elel之间的区别?

javascript backbone.js backbone-views
4个回答
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对象。


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

What is a cached jQuery object?

它是一个分配给变量以供重用的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
投票

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

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


1
投票

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

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

this.el是原生的DOM元素,不受jQuery的影响。

© www.soinside.com 2019 - 2024. All rights reserved.