


An in-depth analysis of the role of Underscore.js, a dependency library of the Backbone.js framework_Basic knowledge
バックボーンは、underscore.js に依存して使用する必要があり、アンダースコア内の関数を使用して、ページ要素へのアクセスと要素の処理の基本操作を完了する必要があります。
注: Backbone は他の JS ライブラリとうまく連携できるため、フレームワークではなくライブラリです。
Underscore はネイティブ オブジェクトを拡張しませんが、_() メソッドを呼び出してカプセル化します。カプセル化が完了すると、js オブジェクトは Underscore オブジェクトになります。また、Value() メソッドを通じてネイティブ js オブジェクトのデータを取得することもできます。アンダースコアオブジェクトの。 (jquery は $() メソッドを通じて Jquery オブジェクトを取得します)
Underscore には合計 60 以上の関数があり、さまざまな処理オブジェクトに応じて、コレクション クラス、配列クラス、関数関数クラス、オブジェクト クラス、ツール関数クラスの 5 つの主要なモジュール カテゴリに分類できます。
アンダースコア template() 関数の説明:
この関数には 3 つのテンプレートが含まれています:
(1): ロジック コードが含まれており、レンダリング後には表示されません。
(2) : データ型、レンダリング後の表示データ。
(3)<%- %>: コード攻撃を避けるために、HTML タグを共通の文字列に変換します。
呼び出し形式:
_.template(templateString, [data], [setting])
双方向のデータ バインディングは実装されていません。
1. アンダースコアオブジェクトのカプセル化
アンダースコアは、ネイティブ JavaScript オブジェクトのプロトタイプ内では拡張されず、jQuery のようなカスタム オブジェクト (以下、「アンダースコア オブジェクト」と呼びます) にデータをカプセル化します。
Underscore オブジェクトの value() メソッドを呼び出すことで、ネイティブ JavaScript データを取得できます。例:
// 定义一个JavaScript内置对象 var jsData = { name : 'data' } // 通过_()方法将对象创建为一个Underscore对象 // underscoreData对象的原型中包含了Underscore中定义的所有方法,你可以任意使用 var underscoreData = _(jsData); // 通过value方法获取原生数据, 即jsData underscoreData.value();
2. 最初に JavaScript 1.6 組み込みメソッドを呼び出します
Underscore の多くのメソッドは JavaScript 1.6 の仕様に含まれているため、Underscore オブジェクト内では、ホスト環境によって提供される組み込みメソッドが最初に呼び出されます (ホスト環境がこれらのメソッドを実装している場合)。機能の実行効率。
JavaScript 1.6 をサポートしていないホスト環境の場合、Underscore は独自の方法でそれを実装します。これは開発者にとって完全に透過的です。
ここで言及するホスティング環境は、Node.js 実行環境またはクライアント ブラウザーです。
3. 名前空間を変更します
アンダースコアは、オブジェクトへのアクセスと作成にデフォルトで _ (アンダースコア) を使用しますが、この名前は命名仕様に準拠していない可能性があり、または簡単に名前の競合を引き起こす可能性があります。
noConflict() メソッドを使用して Underscore の名前を変更し、_ (アンダースコア) 変数の以前の値を復元できます。例:
<script type="text/javascript"> var _ = '自定义变量'; </script> <script type="text/javascript" src="underscore/underscore-min.js"></script> <script type="text/javascript"> // Underscore对象 console.dir(_); // 将Underscore对象重命名为us, 后面都通过us来访问和创建Underscore对象 var us = _.noConflict(); // 输出"自定义变量" console.dir(_); </script>
4. チェーン操作
jQuery でリンク操作を実行する方法を覚えていますか?例:
$('a') .css('position', 'relative') .attr('href', '#') .show();
アンダースコアはチェーン操作もサポートしていますが、最初にchain() メソッドを呼び出して次のように宣言する必要があります。
var arr = [10, 20, 30]; _(arr) .chain() .map(function(item){ return item++; }) .first() .value();
chain() メソッドが呼び出される場合、Underscore は呼び出されたメソッドをクロージャにカプセル化し、戻り値を Underscore オブジェクトとしてカプセル化して次を返します。
// 这是Underscore中实现链式操作的关键函数,它将返回值封装为一个新的Underscore对象,并再次调用chain()方法,为方法链中的下一个函数提供支持。 var result = function(obj, chain) { return chain ? _(obj).chain() : obj; }
5. 拡張アンダースコア
mixin() メソッドを使用してカスタム メソッドを Underscore に簡単に拡張できます。例:
_.mixin({ method1: function(object) { // todo }, method2: function(arr) { // todo }, method3: function(fn) { // todo } });
これらのメソッドは、Underscore のプロトタイプ オブジェクトに追加されます。作成されたすべての Underscore オブジェクトはこれらのメソッドを使用でき、他のメソッドと同じ環境を享受できます。
6. コレクションを調べる
each() メソッドと map() メソッドは、最も一般的に使用される 2 つのメソッドで、コレクション (配列またはオブジェクト) を反復し、コレクション内の各要素を順番に処理するために使用されます。次に例を示します。
var arr = [1, 2, 3]; _(arr).map(function(item, i) { arr[i] = item + 1; }); var obj = { first : 1, second : 2 } _(obj).each(function(value, key) { return obj[key] = value + 1; });
map()方法与each()方法的作用、参数相同,但它会将每次迭代函数返回的结果记录到一个新的数组并返回。
7、函数节流
函数节流是指控制一个函数的执行频率或间隔(就像控制水流的闸门一样),Underscore提供了debounce()和throttle()两个方法用于函数节流。
为了更清楚地描述这两个方法,假设我们需要实现两个需求:
需求1:当用户在文本框输入搜索条件时,自动查询匹配的关键字并提示给用户(就像在Tmall输入搜索关键字时那样)
首先分析第1个需求,我们可以绑定文本框的keypress事件,当输入框内容发生变化时,查询匹配关键字并展示。假设我想查询“windows phone”,它包含13个字符,而我输入完成只花了1秒钟(好像有点快,就意思意思吧),那么在这1秒内,调用了13次查询方法。这是一件非常恐怖的事情,如果Tmall也这样实现,我担心它会不会在光棍节到来之前就挂掉了(当然,它并没有这么脆弱,但这绝对不是最好的方案)
更好的方法是,我们希望用户已经输入完成,或者正在等待提示(也许他懒得再输入后面的内容)的时候,再查询匹配关键字。
最后我们发现,在我们期望的这两种情况下,用户会暂时停止输入,于是我们决定在用户暂停输入200毫秒后再进行查询(如果用户在不断地输入内容,那么我们认为他可能很明确自己想要的关键字,所以等一等再提示他)
这时,利用Underscore中的debounce()函数,我们可以轻松实现这个需求:
<input type="text" id="search" name="search" /> <script type="text/javascript"> var query = _(function() { // 在这里进行查询操作 }).debounce(200); $('#search').bind('keypress', query); </script>
你能看到,我们的代码非常简洁,节流控制在debounce()方法中已经被实现,我们只告诉它当query函数在200毫秒内没有被调用过的话,就执行我们的查询操作,然后再将query函数绑定到输入框的keypress事件。
query函数是怎么来的?我们在调用debounce()方法时,会传递一个执行查询操作的函数和一个时间(毫秒数),debounce()方法会根据我们传递的时间对函数进行节流控制,并返回一个新的函数(即query函数),我们可以放心大胆地调用query函数,而debounce()方法会按要求帮我们做好控制。
需求2:当用户拖动浏览器滚动条时,调用服务器接口检查是否有新的内容
再来分析第2个需求,我们可以将查询方法绑定到window.onscroll事件,但这显然不是一个好的做法,因为用户拖动一次滚动条可能会触发几十次甚至上百次onscroll事件。
我们是否可以使用上面的debounce()方法来进行节流控制?当用户拖动滚动条完毕后,再查询新的内容?但这与需求不符,用户希望在拖动的过程中也能看到新内容的变化。
因此我们决定这样做:用户在拖动时,每两次查询的间隔不少于500毫秒,如果用户拖动了1秒钟,这可能会触发200次onscroll事件,但我们最多只进行2次查询。
利用Underscore中的throttle()方法,我们也可以轻松实现这个需求:
<script type="text/javascript"> var query = _(function() { // 在这里进行查询操作 }).throttle(500); $(window).bind('scroll', query); </script>
代码仍然十分简洁,因为在throttle()方法内部,已经为我们实现的所有控制。
你可能已经发现,debounce()和throttle()两个方法非常相似(包括调用方式和返回值),作用却又有不同。
它们都是用于函数节流,控制函数不被频繁地调用,节省客户端及服务器资源。
debounce()方法关注函数执行的间隔,即函数两次的调用时间不能小于指定时间。
throttle()方法更关注函数的执行频率,即在指定频率内函数只会被调用一次。
8、模板解析
Underscore提供了一个轻量级的模板解析函数,它可以帮助我们有效地组织页面结构和逻辑。
我将通过一个例子来介绍它:
<!-- 用于显示渲染后的标签 --> <ul id="element"></ul> <!-- 定义模板,将模板内容放到一个script标签中 --> <script type="text/template" id="tpl"> <% for(var i = 0; i < list.length; i++) { %> <% var item = list[i] %> <li> <span><%=item.firstName%> <%=item.lastName%></span> <span><%-item.city%></span> </li> <% } %> </script> <script type="text/javascript" src="underscore/underscore-min.js"></script> <script type="text/javascript"> // 获取渲染元素和模板内容 var element = $('#element'), tpl = $('#tpl').html(); // 创建数据, 这些数据可能是你从服务器获取的 var data = { list: [ {firstName: '<a href="#">Zhang</a>', lastName: 'San', city: 'Shanghai'}, {firstName: 'Li', lastName: 'Si', city: '<a href="#">Beijing</a>'}, {firstName: 'Wang', lastName: 'Wu', city: 'Guangzhou'}, {firstName: 'Zhao', lastName: 'Liu', city: 'Shenzhen'} ] } // 解析模板, 返回解析后的内容 var html = _.template(tpl, data); // 将解析后的内容填充到渲染元素 element.html(html); </script>
在本例中,我们将模板内容放到一个

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
