我正试图围绕这个概念。
你能否为我愚蠢,并提供一个简单的例子,说明el:
属性和tagName:
属性之间的区别?
在某些示例中,不同的视图有时使用el:
,而其他视图则使用tagName:
。
我特意搞乱了我自己对此example
的实现答案 0 :(得分:17)
区别在于:
el应该用于保留对表示整个视图的实际DOM节点的引用。
这意味着您可以使用jQuery或w / e轻松地对其执行操作。 $(this.el).hide()或$(this.el).html('我现在是Jquery对象');
TagName只是一个字符串,用于确定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,在这种情况下tagName是无关紧要的:
var myView = new view({ el: $("someExistingEl") });
答案 1 :(得分:-3)
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();
我认为应该可以正常工作。