diff --git a/index.html b/index.html index e8d310c76..1a613a16f 100644 --- a/index.html +++ b/index.html @@ -3,7 +3,7 @@
- +You may also read through the annotated source code.
@@ -327,7 +328,7 @@
sortBy_.sortBy(list, iterator, [context])
- Returns a sorted copy of list, ranked in ascending order by the
+ Returns a sorted copy of list, ranked in ascending order by the
results of running each value through iterator.
@@ -565,7 +566,7 @@ _.sortedIndex([10, 20, 30, 40, 50], 35);
shuffle_.shuffle(list)
- Returns a shuffled copy of the list, using a version of the
+ Returns a shuffled copy of the list, using a version of the
Fisher-Yates shuffle.
@@ -751,7 +752,7 @@ _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
Returns the index at which value can be found in the array,
or -1 if value is not present in the array. Uses the native
- indexOf function unless it's missing. If you're working with a
+ indexOf function unless it's missing. If you're working with a
large array, and you know that the array is already sorted, pass true
for isSorted to use a faster binary search.
@@ -836,7 +837,7 @@ jQuery('#underscore_button').bind('click', buttonView.onClick);
memoize_.memoize(function, [hashFunction])
Memoizes a given function by caching the computed result. Useful
- for speeding up slow-running computations. If passed an optional
+ for speeding up slow-running computations. If passed an optional
hashFunction, it will be used to compute the hash key for storing
the result, based on the arguments to the original function. The default
hashFunction just uses the first argument to the memoized function
@@ -877,8 +878,8 @@ _.defer(function(){ alert('deferred'); });
throttle_.throttle(function, wait)
- Creates and returns a new, throttled version of the passed function,
- that, when invoked repeatedly, will only actually call the original function
+ Creates and returns a new, throttled version of the passed function,
+ that, when invoked repeatedly, will only actually call the original function
at most once per every wait
milliseconds. Useful for rate-limiting events that occur faster than you
can keep up with.
@@ -892,11 +893,11 @@ $(window).scroll(throttled);
debounce_.debounce(function, wait)
Creates and returns a new debounced version of the passed function that
- will postpone its execution until after
- wait milliseconds have elapsed since the last time it
- was invoked. Useful for implementing behavior that should only happen
- after the input has stopped arriving. For example: rendering a
- preview of a Markdown comment, recalculating a layout after the window
+ will postpone its execution until after
+ wait milliseconds have elapsed since the last time it
+ was invoked. Useful for implementing behavior that should only happen
+ after the input has stopped arriving. For example: rendering a
+ preview of a Markdown comment, recalculating a layout after the window
has stopped being resized, and so on.
@@ -907,7 +908,7 @@ $(window).resize(lazyLayout);
once_.once(function)
- Creates a version of the function that can only be called one time.
+ Creates a version of the function that can only be called one time.
Repeated calls to the modified function will have no effect, returning
the value from the original call. Useful for initialization functions,
instead of having to set a boolean flag and then check it later.
@@ -922,7 +923,7 @@ initialize();
after_.after(count, function)
- Creates a version of the function that will only be run after first
+ Creates a version of the function that will only be run after first
being called count times. Useful for grouping asynchronous responses,
where you want to be sure that all the async calls have finished, before
proceeding.
@@ -930,7 +931,7 @@ initialize();
var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
- note.asyncSave({success: renderNotes});
+ note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved.
@@ -1058,9 +1059,9 @@ _.chain([1,2,3,200])
has_.has(object, key)
- Does the object contain the given key? Identical to
+ Does the object contain the given key? Identical to
object.hasOwnProperty(key), but uses a safe reference to the
- hasOwnProperty function, in case it's been
+ hasOwnProperty function, in case it's been
overridden accidentally.
@@ -1238,7 +1239,7 @@ _.isNull(undefined);
_.isUndefined(window.missingVariable);
=> true
-
+
Utility Functions
@@ -1275,7 +1276,7 @@ _(3).times(function(){ genie.grantWish(); });
mixin_.mixin(object)
Allows you to extend Underscore with your own utility functions. Pass
- a hash of {name: function} definitions to have your functions
+ a hash of {name: function} definitions to have your functions
added to the Underscore object, as well as the OOP wrapper.
@@ -1302,19 +1303,31 @@ _.uniqueId('contact_');
escape_.escape(string)
- Escapes a string for insertion into HTML, replacing
+ Escapes a string for insertion into HTML, replacing
&, <, >, ", ', and / characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
+
+ result_.result(object, property)
+
+ If the value of the named property is a function then invoke it; otherwise, return it.
+
+
+var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
+_.result(object, 'cheese');
+=> "crumpets"
+_.result(object, 'stuff');
+=> "nonsense"
+
template_.template(templateString, [context])
Compiles JavaScript templates into functions that can be evaluated
for rendering. Useful for rendering complicated bits of HTML from JSON
- data sources. Template functions can both interpolate variables, using
+ data sources. Template functions can both interpolate variables, using
<%= … %>, as well as execute arbitrary JavaScript code, with
<% … %>. If you wish to interpolate a value, and have
it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a
@@ -1340,7 +1353,7 @@ template({value : '<script>'});
You can also use print from within JavaScript code. This is
sometimes more convenient than using <%= ... %>.
-
+
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
@@ -1349,8 +1362,8 @@ compiled({epithet: "stooge"});
If ERB-style delimiters aren't your cup of tea, you can change Underscore's
template settings to use different symbols to set off interpolated code.
- Define an interpolate regex to match expressions that should be
- interpolated verbatim, an escape regex to match expressions that should
+ Define an interpolate regex to match expressions that should be
+ interpolated verbatim, an escape regex to match expressions that should
be inserted after being HTML escaped, and an evaluate regex to match
expressions that should be evaluated without insertion into the resulting
string. You may define or omit any combination of the three.
@@ -1368,6 +1381,18 @@ var template = _.template("Hello {{ name }}!");
template({name : "Mustache"});
=> "Hello Mustache!"
+
+ Precompiling your templates can be a big help when debugging errors you can't
+ reproduce. This is because precompiled templates can provide line numbers and
+ a stack trace, something that is not possible when compiling templates on the client.
+ template provides the source property on the compiled template
+ function for easy precompilation.
+
+
+ <script>
+ JST.project = <%= _.template(jstText).source %>;
+</script>
+
Chaining
@@ -1450,7 +1475,7 @@ _([1, 2, 3]).value();
The source is
available on GitHub.
-
+
Underscore.php,
a PHP port of the functions that are applicable in both languages.
@@ -1458,17 +1483,17 @@ _([1, 2, 3]).value();
The source is
available on GitHub.
-
+
Underscore-perl,
- a Perl port of many of the Underscore.js functions,
- aimed at on Perl hashes and arrays, also
+ a Perl port of many of the Underscore.js functions,
+ aimed at on Perl hashes and arrays, also
available on GitHub.
-
+
Underscore.string,
- an Underscore extension that adds functions for string-manipulation:
+ an Underscore extension that adds functions for string-manipulation:
trim, startsWith, contains, capitalize,
reverse, sprintf, and more.
@@ -1487,7 +1512,7 @@ _([1, 2, 3]).value();
Functional JavaScript,
which includes comprehensive higher-order function support as well as string lambdas.
-
+
Michael Aufreiter's Data.js,
a data manipulation + persistence library for JavaScript.
@@ -1498,7 +1523,7 @@ _([1, 2, 3]).value();
Change Log
-
+
1.3.1 — Jan. 23, 2012
1.3.0 — Jan. 11, 2012
1.2.4 — Jan. 4, 2012
1.2.3 — Dec. 7, 2011
1.2.2 — Nov. 14, 2011
1.2.1 — Oct. 24, 2011
1.2.0 — Oct. 5, 2011
1.1.7 — July 13, 2011
Added _.groupBy, which aggregates a collection into groups of like items.
- Added _.union and _.difference, to complement the
+ Added _.union and _.difference, to complement the
(re-named) _.intersection.
Various improvements for support of sparse arrays.
_.toArray now returns a clone, if directly passed an array.
_.functions now also returns the names of functions that are present
in the prototype chain.
1.1.6 — April 18, 2011
Added _.after, which will return a function that only runs after
@@ -1684,30 +1709,30 @@ _([1, 2, 3]).value();
_.extend no longer copies keys when the value is undefined.
_.bind now errors when trying to bind an undefined value.
1.1.5 — Mar 20, 2011
Added an _.defaults function, for use merging together JS objects
representing default options.
Added an _.once function, for manufacturing functions that should
only ever execute a single time.
- _.bind now delegates to the native ECMAScript 5 version,
+ _.bind now delegates to the native ECMAScript 5 version,
where available.
_.keys now throws an error when used on non-Object values, as in
ECMAScript 5.
Fixed a bug with _.keys when used over sparse arrays.
1.1.4 — Jan 9, 2011
- Improved compliance with ES5's Array methods when passing null
+ Improved compliance with ES5's Array methods when passing null
as a value. _.wrap now correctly sets this for the
wrapped function. _.indexOf now takes an optional flag for
finding the insertion index in an array that is guaranteed to already
be sorted. Avoiding the use of .callee, to allow _.isArray
to work properly in ES5's strict mode.
1.1.3 — Dec 1, 2010
In CommonJS, Underscore may now be required with just:
@@ -1719,26 +1744,26 @@ _([1, 2, 3]).value();
Improved the isType family of functions for better interoperability
with Internet Explorer host objects.
_.template now correctly escapes backslashes in templates.
- Improved _.reduce compatibility with the ECMA5 version:
+ Improved _.reduce compatibility with the ECMA5 version:
if you don't pass an initial value, the first item in the collection is used.
_.each no longer returns the iterated collection, for improved
consistency with ES5's forEach.
1.1.2
- Fixed _.contains, which was mistakenly pointing at
- _.intersect instead of _.include, like it should
+ Fixed _.contains, which was mistakenly pointing at
+ _.intersect instead of _.include, like it should
have been. Added _.unique as an alias for _.uniq.
1.1.1
Improved the speed of _.template, and its handling of multiline
- interpolations. Ryan Tenney contributed optimizations to many Underscore
+ interpolations. Ryan Tenney contributed optimizations to many Underscore
functions. An annotated version of the source code is now available.
1.1.0
The method signature of _.reduce has been changed to match
@@ -1747,33 +1772,33 @@ _([1, 2, 3]).value();
called with no arguments, and preserves whitespace. _.contains
is a new alias for _.include.
1.0.4
- Andri Möll contributed the _.memoize
- function, which can be used to speed up expensive repeated computations
+ Andri Möll contributed the _.memoize
+ function, which can be used to speed up expensive repeated computations
by caching the results.
1.0.3
Patch that makes _.isEqual return false if any property
of the compared object has a NaN value. Technically the correct
thing to do, but of questionable semantics. Watch out for NaN comparisons.
1.0.2
Fixes _.isArguments in recent versions of Opera, which have
arguments objects as real Arrays.
1.0.1
- Bugfix for _.isEqual, when comparing two objects with the same
+ Bugfix for _.isEqual, when comparing two objects with the same
number of undefined keys, but with different names.
1.0.0
Things have been stable for many months now, so Underscore is now
@@ -1781,15 +1806,15 @@ _([1, 2, 3]).value();
include _.isBoolean, and the ability to have _.extend
take multiple source objects.
0.6.0
- Major release. Incorporates a number of
+ Major release. Incorporates a number of
Mile Frawley's refactors for
safer duck-typing on collection functions, and cleaner internals. A new
_.mixin method that allows you to extend Underscore with utility
- functions of your own. Added _.times, which works the same as in
- Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray,
+ functions of your own. Added _.times, which works the same as in
+ Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray,
and Object.keys.
\u2028<%= "\\u2028\\u2029" %>\u2029
'); + strictEqual(tmpl(), '\u2028\u2028\u2029\u2029
'); + }); + + test('result calls functions and returns primitives', function() { + var obj = {w: '', x: 'x', y: function(){ return this.x; }}; + strictEqual(_.result(obj, 'w'), ''); + strictEqual(_.result(obj, 'x'), 'x'); + strictEqual(_.result(obj, 'y'), 'x'); + strictEqual(_.result(obj, 'z'), undefined); + strictEqual(_.result(null, 'x'), null); + }); + }); diff --git a/underscore.js b/underscore.js index 88da6e1d8..44226a07c 100644 --- a/underscore.js +++ b/underscore.js @@ -309,7 +309,7 @@ // Return the number of elements in an object. _.size = function(obj) { - return _.toArray(obj).length; + return _.isArray(obj) ? obj.length : _.keys(obj).length; }; // Array Functions @@ -873,6 +873,14 @@ return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/'); }; + // If the value of the named property is a function then invoke it; + // otherwise, return it. + _.result = function(object, property) { + if (object == null) return null; + var value = object[property]; + return _.isFunction(value) ? value.call(object) : value; + }; + // Add your own custom functions to the Underscore object, ensuring that // they're correctly added to the OOP wrapper as well. _.mixin = function(obj) { @@ -902,39 +910,58 @@ // guaranteed not to match. var noMatch = /.^/; + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + '\\': '\\', + "'": "'", + 'r': '\r', + 'n': '\n', + 't': '\t', + 'u2028': '\u2028', + 'u2029': '\u2029' + }; + + for (var p in escapes) escapes[escapes[p]] = p; + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g; + // Within an interpolation, evaluation, or escaping, remove HTML escaping // that had been previously added. var unescape = function(code) { - return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'"); + return code.replace(unescaper, function(match, escape) { + return escapes[escape]; + }); }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(str, data) { - var c = _.templateSettings; - var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + + var settings = _.templateSettings; + var source = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + 'with(obj||{}){__p.push(\'' + - str.replace(/\\/g, '\\\\') - .replace(/'/g, "\\'") - .replace(c.escape || noMatch, function(match, code) { - return "',_.escape(" + unescape(code) + "),'"; - }) - .replace(c.interpolate || noMatch, function(match, code) { - return "'," + unescape(code) + ",'"; - }) - .replace(c.evaluate || noMatch, function(match, code) { - return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('"; - }) - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/\t/g, '\\t') - + "');}return __p.join('');"; - var func = new Function('obj', '_', tmpl); - if (data) return func(data, _); - return function(data) { - return func.call(this, data, _); + str + .replace(escaper, function(match) { + return '\\' + escapes[match]; + }) + .replace(settings.escape || noMatch, function(match, code) { + return "',\n_.escape(" + unescape(code) + "),\n'"; + }) + .replace(settings.interpolate || noMatch, function(match, code) { + return "',\n" + unescape(code) + ",\n'"; + }) + .replace(settings.evaluate || noMatch, function(match, code) { + return "');\n" + unescape(code) + "\n;__p.push('"; + }) + + "');\n}\nreturn __p.join('');"; + var render = new Function('obj', '_', source); + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); }; + template.source = 'function(obj){\n' + source + '\n}'; + return template; }; // Add a "chain" function, which will delegate to the wrapper.