【问题标题】:Backbone: Why assign `$('#footer')` to `el`? [duplicate]Backbone:为什么将 `$('#footer')` 分配给 `el`? [复制]
【发布时间】:2017-03-12 07:31:50
【问题描述】:

我发现了以下语句:

el: '#footer'

var todosView = new TodosView({el: $('#footer')});

为什么将$('#footer') 分配给el?这让我很困惑。我在这里看到了What is the difference between $el and el in Backbone.js views? 的帖子,仍然一头雾水。

另外,我读到: view.$el 属性等价于$(view.el)view.$(selector) 等价于$(view.el).find(selector)。在 TodoView 示例的 render 方法中,我们看到 this.$el 用于设置元素的 HTML,this.$() 用于查找类“edit”的子元素。

但是,有人说 If you call $(this.el), your just keep executing the jquery selector to get the same jquery object. '$el' is the cached version of $(this.el)

什么是“缓存版本”?

【问题讨论】:

标签: javascript backbone.js


【解决方案1】:

$elel 有什么区别?

el view property

this.el 可以从 DOM 选择器字符串或元素中解析; 否则将从视图的tagNameclassNameid 创建 和attributes 属性。如果没有设置,this.el 是一个空的div, 这通常很好。

它是一个 DOM 元素对象引用。 不要直接设置el,如果要更改,请改用view.setElement method

$el property

视图元素的缓存 jQuery 对象。方便的参考 而不是一直重新包装 DOM 元素。

我喜欢用户mu is too short puts it

this.$el = $(this.el);

另外不要直接设置$el使用view.setElement method

el 选项

el 引用也可以传递给视图的构造函数。

new Backbone.View({ el: '#element' });
new Backbone.View({ el: $('#element') }); // unecessary

它覆盖el 属性,然后用于$el 属性。

如果传递了选择器字符串,则将其替换为它所代表的 DOM 元素。

为什么要将$('#footer') 分配给el?

this.el 可以是 jQuery 对象。您可以看到 Backbone 确保 el 是一个 DOM 元素,$el 是它在 _setElement function 中的一个 jQuery 对象:

_setElement: function(el) {
  this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
  this.el = this.$el[0];
},

这说明了为什么this.$el 等同于$(this.el)

但是Backbone.$ 是什么?

Backbone 保持对 $ 的引用。

对于 Backbone 的目的,jQuery、Zepto、Ender 或 My Library(开玩笑) 拥有$ 变量。

在我们的例子中,$ 是 jQuery,所以 Backbone.$ 只是 jQuery,但是 Backbone 依赖是灵活的:

Backbone 唯一的硬依赖是 Underscore.js ( >= 1.8.3)。为了 使用 Backbone.View 的 RESTful 持久性和 DOM 操作,包括 jQuery ( >= 1.11.0) 和 json2.js 用于旧版 Internet Explorer 支持。 (模仿下划线和 jQuery API,例如 LodashZepto, 也倾向于工作,具有不同程度的兼容性。)

this.$(selector) 等价于 $(view.el).find(selector)

其实效率更高一点$ view function 只是:

$: function(selector) {
  return this.$el.find(selector);
},

什么是缓存的 jQuery 对象?

在这种情况下,它只意味着一个 jQuery 对象被保存在一个变量中,该变量在视图中被重用。避免了每次用$(selector)查找元素的代价高昂的操作。

您可以(并且应该)尽可能使用这个小优化,比如在 render 函数中:

render: function() {
    this.$el.html(this.template(/* ...snip... */));
    // this is caching a jQuery object
    this.$myCachedObject = this.$('.selector');
},

onExampleEvent: function(e) {
    // avoids $('.selector') here and on any sub-sequent example events.
    this.$myCachedObject.toggleClass('example');
}

在 jQuery 缓存对象变量前加上 $ 只是一个标准,而不是要求。


Backbone 的源代码不到 2000 行,文档齐全且易于阅读。我强烈鼓励大家深入研究它以轻松理解底层逻辑。

他们还提供了一个annotated source page,它更易于阅读。

补充阅读

【讨论】:

  • 谢谢。非常明确的答案。但是你能解释一下 Backbone.$ 吗?
  • @BAE 我完全可以!
  • 谢谢。我愿意阅读Backbone的源代码,但是你知道有什么好的帖子可以帮助我理解源代码吗?
  • @BAE 我想我已经完成了
猜你喜欢
  • 2013-04-04
  • 2012-12-24
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2017-07-31
  • 2019-02-25
  • 1970-01-01
相关资源
最近更新 更多