[英]What is the difference between $el and el in Backbone.js views?
你能否在Backbone.js視圖中告訴$el
和el
之間的區別?
讓我們說你這樣做
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);
並且很容易理解為什么,請查看視圖的_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對象。 它避免了每次使用$(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');
}
看到我寫的更廣泛的答案了解更多。
簡而言之,el允許您訪問HTML DOM元素,即您可以引用和訪問它們,而$ el是圍繞el的jQuery包裝器。
$ el不僅提供對特定DOM元素的訪問,而且它充當jQuery選擇器,並且您有權在特定DOM元素上使用jQuery庫函數,如show(),hide()等。
回答它已經太晚了但是 - > this.$el
是jQuery上下文中元素的引用 ,通常用於.html()
或.addClass()
類的東西等。例如,如果你有一個id為someDiv的div,你將它設置為Backbone視圖的el屬性,以下語句是相同的:
this.$el.html() $("#someDiv").html() $(this.el).html()
this.el
是本機DOM元素,不受jQuery的影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.