Merge pull request #512 from braddunbar/getvalue

Add utility function `result`.
This commit is contained in:
brad dunbar
2012-03-19 11:46:26 -07:00
3 changed files with 120 additions and 91 deletions

View File

@@ -245,6 +245,7 @@
<li>- <a href="#mixin">mixin</a></li> <li>- <a href="#mixin">mixin</a></li>
<li>- <a href="#uniqueId">uniqueId</a></li> <li>- <a href="#uniqueId">uniqueId</a></li>
<li>- <a href="#escape">escape</a></li> <li>- <a href="#escape">escape</a></li>
<li>- <a href="#result">result</a></li>
<li>- <a href="#template">template</a></li> <li>- <a href="#template">template</a></li>
</ul> </ul>
@@ -1309,6 +1310,18 @@ _.uniqueId('contact_');
_.escape('Curly, Larry &amp; Moe'); _.escape('Curly, Larry &amp; Moe');
=&gt; "Curly, Larry &amp;amp; Moe"</pre> =&gt; "Curly, Larry &amp;amp; Moe"</pre>
<p id="result">
<b class="header">result</b><code>_.result(object, property)</code>
<br />
Returns a value from an object as a property or as a function.
</p>
<pre>
var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=&gt; "crumpets"
_.result(object, 'stuff');
=&gt; "nonsense"</pre>
<p id="template"> <p id="template">
<b class="header">template</b><code>_.template(templateString, [context])</code> <b class="header">template</b><code>_.template(templateString, [context])</code>
<br /> <br />

View File

@@ -165,4 +165,13 @@ $(document).ready(function() {
strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>'); strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>');
}); });
test('result calls functions and returns primitives', function() {
var obj = {w: '', x: 'x', y: function(){ return 'y'; }};
strictEqual(_.result(obj, 'w'), '');
strictEqual(_.result(obj, 'x'), 'x');
strictEqual(_.result(obj, 'y'), 'y');
strictEqual(_.result(obj, 'z'), undefined);
strictEqual(_.result(null, 'x'), null);
});
}); });

View File

@@ -873,6 +873,13 @@
return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
}; };
// Get a value from an object as a property or as a function.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value() : value;
};
// Add your own custom functions to the Underscore object, ensuring that // Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well. // they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) { _.mixin = function(obj) {