nodejs:underscore模塊介紹

underscore模塊介紹

文檔

參考描述

1、Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. 

2、Underscore 是一個 JavaScript 工具庫,它提供了一整套函數式編程的實用功能,但是沒有擴展任何 JavaScript 內置對象。 他解決了這個問題:“如果我面對一個空白的 HTML 頁面,並希望立即開始工作,我需要什麼?” 他彌補了 jQuery 沒有實現的功能,同時又是 Backbone 必不可少的部分。

Underscore 提供了100多個函數,包括常用的:map、filter、invoke — 當然還有更多專業的輔助函數,如:函數綁定、JavaScript 模板功能、創建快速索引、強類型相等測試等等。

模板語法介紹:

  • <%= %>, 中間寫表達式
  • <% %>, 中間寫語句

參考寫法

  • 提示:underscore庫建議使用’_'來命名對象,類似於jQuery使用$來命名

// 案例一:
var html = '<h1><%= name %></h1>';
var compiled = _.template(html);
var result = compiled({name: 'aaaa'});
console.log(compiled);



// 案例二:
// 構建模板字符串
var html = '<%for (var i = 0; i < 5; i++) { %><h1><%= name %></h1><% }%>';

// 編譯模板
var compiled = _.template(html);

// 進行模板字符串替換
var result = compiled({name: '張三'});

// 輸出後的結果
console.log(result);

underscore中_.template()函數返回值其實就是一個函數:

function(obj){
  var __t;
  var __p = '';
  var __j = Array.prototype.join,print = function () {
    __p += __j.call(arguments,'');
  };

  with(obj||{}) {
    __p += '<h1>' + ((__t = (name)) == null ? '' : __t) + '</h1>';
  }
  return __p;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章