为什么用这个。$(选择)。方法()与骨干语法? [英] Why using the this.$(selector).method() syntax with backbone?

查看:108
本文介绍了为什么用这个。$(选择)。方法()与骨干语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看这一堆code在教程:

I have seen this bunch of code in a tutorial:

var searchTerm = this.$('#searchTerm').val().trim();

我想了解的效用这一点。在选择面前,这是我第一次看到。

I would like to understand the utility of the this. in front of the selector, it's the first time i see that.

推荐答案

Backbone.View 这一点。$ 给出的jQuery的作用域版本。事实上,这是等同于使用这一点。$ el.find 而这又相当于使用 $(this.el).find

In a Backbone.View, this.$ gives a scoped version of jQuery. It is in fact equivalent to using this.$el.find which is in turn equivalent to using $(this.el).find.

总之,原因是使用它,它只会从视图的元素/渲染的模板内访问HTML元素是个好主意。因此,你不必担心HTML页面的其余部分,你会始终选择您期望的元素。

Anyhow, the reason it is a good idea to use it is that it will only access html elements from within the view's element/rendered template. Thus, you don't have to worry about the rest of the html page and you will always select the element you expect to.

假设你有一个生成子视图和每一种都有一个可编辑区域的视图。如果你不使用jQuery的范围版本,以获得正确的编辑字段,你将不得不放弃了独特的 ID 来每一个HTML元素,以确保你会检索它的内容时选择是正确的。在另一方面,如果你使用的范围的版本,你就只能给这个编辑领域的属性,然后选择该类会给你一个独特的元素,右之一。

Imagine that you have a view that spawns sub-views and that each of these have an editable field. If you don't use the scoped version of jQuery to get the right editable field, you will have to give a unique id to each of these html elements to make sure you will select the right one when retrieving it's content. On the other hand, if you use the scoped version, you will just have to give this editable field a class attribute and selecting this class will give you a unique element, the right one.

这篇关于为什么用这个。$(选择)。方法()与骨干语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆