我試圖圍繞這個概念我的頭。BackboneJs:在一個視圖是什麼區別el:和tagName:
你可以貶低這個對我來說,也許提供el:
屬性和tagName:
屬性之間的差異的簡單例子嗎?
在一些示例中,不同視圖有時使用el:
,而其他使用tagName:
。
我專門亂搞與我自己實現這個example
我試圖圍繞這個概念我的頭。BackboneJs:在一個視圖是什麼區別el:和tagName:
你可以貶低這個對我來說,也許提供el:
屬性和tagName:
屬性之間的差異的簡單例子嗎?
在一些示例中,不同視圖有時使用el:
,而其他使用tagName:
。
我專門亂搞與我自己實現這個example
的區別是這樣的:
EL應該被用來保存到代表觀點作爲一個整體的實際DOM節點的引用。
這意味着您可以使用jQuery或w/e輕鬆地對其執行操作。 $(this.el).hide()或$(this.el).html('我現在是一個Jquery對象');
TagName只是一個字符串,用於確定EL節點el的類型。默認值是div,但如果你想要的話,你可以將它設爲任何你喜歡的HTML元素。
考慮:
var view = Backbone.View.extend({
tagName: 'p',
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
$(this.el).html('I am a jQuery-ized paragraph');
return this;
}
});
$(document.body).append(new view().render().el);
你可能會運行到的問題是,有時你在一個視圖的實例,在這種情況下標記名是無關緊要的設置EL:
var myView = new view({ el: $("someExistingEl") });
所以他們永遠不會一起使用? –
它們不能一起使用。如果你直接指定一個'el',你的'tagName'將被忽略。 –
他們可以一起使用,你只是不能明確地設置this.el = $(somethingelse),並期望它兌現this.tagName。如果你確實使用$(this.el).html('some stuff'),它會在this.tagName之內。 –
var View = Backbone.View.extend({
tagName: 'span',
id: 'identity',
class: 'classy',
el: $(this.tagName), // or
el: $('<' + this.tagName + ' />', {
id: this.id, // identity
'class': this.class // classy
}) // this is jQuery shorthand for building an element fyi
});
var view = new View();
我認爲應該可以正常工作。
'這個'在'el:$(this.tagName)'中不會是你想象的那樣。 –
el會引用我們DOM中的現有元素,而tagName我們將創建一個新的dom元素,如果給定了tagName和className。 – STEEL