0.4.0 is out, with OOP-style and chaining

This commit is contained in:
Jeremy Ashkenas
2009-11-07 14:29:40 -05:00
parent 4f0afda61c
commit ed37b9df49
6 changed files with 135 additions and 13 deletions

View File

@@ -18,8 +18,8 @@
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions.
var wrapper = function(obj) { this.wrapped = obj; };
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Create a safe reference to the Underscore object for reference below.
var _ = root._ = function(obj) { return new wrapper(obj); };
@@ -28,7 +28,7 @@
if (typeof exports !== 'undefined') _ = exports;
// Current version.
_.VERSION = '0.3.3';
_.VERSION = '0.4.0';
/*------------------------ Collection Functions: ---------------------------*/
@@ -447,8 +447,9 @@
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = this._idCounter = (this._idCounter || 0) + 1;
var id = idCounter++;
return prefix ? prefix + id : id;
};
@@ -456,7 +457,7 @@
_.functions = function() {
var functions = [];
for (var key in _) if (Object.prototype.hasOwnProperty.call(_, key)) functions.push(key);
return _.without(functions, 'VERSION', 'prototype', 'noConflict');
return _.without(functions, 'VERSION', 'prototype', 'noConflict').sort();
};
// JavaScript templating a-la ERB, pilfered from John Resig's
@@ -487,13 +488,26 @@
_.some = _.any;
_.methods = _.functions;
/*------------------- Add all Functions to the Wrapper: --------------------*/
/*------------------------ Setup the OOP Wrapper: --------------------------*/
// Add all of the Underscore functions to the wrapper object.
_.each(_.functions(), function(name) {
wrapper.prototype[name] = function() {
Array.prototype.unshift.call(arguments, this.wrapped);
return _[name].apply(_, arguments);
Array.prototype.unshift.call(arguments, this._wrapped);
var result = _[name].apply(_, arguments);
return this._chain ? _(result).chain() : result;
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.get = function() {
return this._wrapped;
};
})();