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

新手上路,请多包涵

您能说出 Backbone.js 视图中 $elel 之间的区别吗?

原文由 ali asad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 389
2 个回答
"el"  is HTMLElement
"$el" is jQuery


让我们说你这样做

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对象。

原文由 Rayweb_on 发布,翻译遵循 CC BY-SA 4.0 许可协议

mu 太短 是完全正确的:

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

很容易理解为什么,看看 [视图的 `_setElement` 函数](https://github.com/jashkenas/backbone/blob/8ec88604732944f197b352a6be22c8216ea9d3a1/backbone.js#L1285):

> ```
>  _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 对象?

它是一个分配给变量以供重用的 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’); }

”`

请参阅我写的 广泛答案 以了解更多信息。

原文由 Emile Bergeron 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题