Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Updated Underscore, Underscore-Awesomer, Mixin and Backbone-relationa…

…l. Moved qunit files.
  • Loading branch information...
commit 87395784dbdc3dbcb771862b356b8f6dbe90aa2a 1 parent 68b4f40
@kmalakoff authored
View
6 config/assets.yaml
@@ -2,6 +2,6 @@ gzip_assets: off
compress_assets: off
javascripts:
- 'lib':
- - lib/build/date_extensions.js
- - lib/build/localized_string.js
+ 'examples_lib':
+ - examples_lib/build/date_extensions.js
+ - examples_lib/build/localized_string.js
View
2  ex_backbone_articulation_js/test.html
@@ -14,7 +14,7 @@
<script type="text/javascript" src="../vendor/backbone-articulation.js"></script> <!-- THE LIBRARY FOR THE EXAMPLES -->
<!-- HELPERS - BUT NOT REQUIRED/DEPENDENCIES -->
- <script type="text/javascript" src="../lib/build/lib.js"></script>
+ <script type="text/javascript" src="../examples_lib/build/examples_lib.js"></script>
<!-- EXAMPLES (look at test.coffee for a commented and more readable version) -->
<script type="text/javascript" src="build/test.js"></script>
View
2  ex_combined_examples/test.html
@@ -14,7 +14,7 @@
<script type="text/javascript" src="../vendor/backbone-articulation.js"></script>
<script type="text/javascript" src="../vendor/mixin.js"></script>
<script type="text/javascript" src="../vendor/background.js"></script>
- <script type="text/javascript" src="../lib/build/lib.js"></script>
+ <script type="text/javascript" src="../examples_lib/build/examples_lib.js"></script>
<!-- EXAMPLES (look at test.coffee for a commented and more readable version) -->
<script type="text/javascript" src="build/test.js"></script>
View
2  ex_mixin_js/test.html
@@ -18,7 +18,7 @@
<script type="text/javascript" src="../vendor/mixin.js"></script> <!-- THE LIBRARY FOR THE EXAMPLES -->
<!-- HELPERS -->
- <script type="text/javascript" src="../lib/build/lib.js"></script>
+ <script type="text/javascript" src="../examples_lib/build/examples_lib.js"></script>
<!-- EXAMPLES (look at test.coffee for a commented and more readable version) -->
<script type="text/javascript" src="build/test.js"></script>
View
0  lib/build/date_extensions.js → examples_lib/build/date_extensions.js
File renamed without changes
View
0  lib/build/lib.js → examples_lib/build/examples_lib.js
File renamed without changes
View
53 examples_lib/build/lib.js
@@ -0,0 +1,53 @@
+Date.prototype.isEqual = function(that) {
+ var that_date_components, this_date_components;
+ this_date_components = this.toJSON();
+ that_date_components = that instanceof Date ? that.toJSON() : that;
+ return _.isEqual(this_date_components, that_date_components);
+};
+Date.prototype.toJSON = function() {
+ return {
+ _type: 'Date',
+ format: 'UTC',
+ year: this.getUTCFullYear(),
+ month: this.getUTCMonth(),
+ day: this.getUTCDate(),
+ hours: this.getUTCHours(),
+ minutes: this.getUTCMinutes(),
+ seconds: this.getUTCSeconds()
+ };
+};
+Date.parseJSON = function(json) {
+ if (json._type !== 'Date') {
+ throw new Error("Date.parseJSON: unrecognized json");
+ }
+ if (json.format !== 'UTC') {
+ throw new Error("Date.parseJSON: unrecognized json");
+ }
+ return new Date(new Date(Date.UTC(json.year, json.month, json.day, json.hours, json.minutes, json.seconds)));
+};
+var LocalizedString, root;
+root = this;
+root.ENV || (root.ENV = {});
+LocalizedString = (function() {
+ function LocalizedString(id) {
+ this.id = id;
+ this.string = (this.id !== void 0) && ENV.LOCALIZED_STRINGS && ENV.LOCALIZED_STRINGS.hasOwnProperty(this.id) ? ENV.LOCALIZED_STRINGS[this.id] : 'undefined';
+ }
+ LocalizedString.prototype.toJSON = function() {
+ if (this.id !== void 0) {
+ return {
+ _type: 'LocalizedString',
+ id: this.id
+ };
+ } else {
+ return null;
+ }
+ };
+ LocalizedString.parseJSON = function(json) {
+ if (json._type !== 'LocalizedString') {
+ throw new Error("LocalizedString.parseJSON: unrecognized json");
+ }
+ return new LocalizedString(json.id);
+ };
+ return LocalizedString;
+})();
View
0  lib/build/localized_string.js → examples_lib/build/localized_string.js
File renamed without changes
View
0  lib/date_extensions.coffee → examples_lib/date_extensions.coffee
File renamed without changes
View
0  lib/localized_string.coffee → examples_lib/localized_string.coffee
File renamed without changes
View
4 script/build.rb
@@ -3,8 +3,8 @@
PROJECT_ROOT = File.expand_path('../..', __FILE__)
# Helper Library
-`cd #{PROJECT_ROOT}; coffee -b -o lib/build -c lib`
-`cd #{PROJECT_ROOT}; jammit -c config/assets.yaml -o lib/build`
+`cd #{PROJECT_ROOT}; coffee -b -o examples_lib/build -c examples_lib`
+`cd #{PROJECT_ROOT}; jammit -c config/assets.yaml -o examples_lib/build`
# Examples for individual libraries
`cd #{PROJECT_ROOT}; coffee -b -o ex_backbone_articulation_js/build -c ex_backbone_articulation_js`
View
2  script/clean.rb
@@ -5,7 +5,7 @@
PROJECT_ROOT = File.expand_path('../..', __FILE__)
CLEAN_PATTERNS = [
# Helper Library
- 'lib/build/**.js',
+ 'examples_lib/build/**.js',
# Examples for individual libraries
'ex_backbone_articulation_js/build/**.js',
View
2  script/watch.rb
@@ -7,7 +7,7 @@
PROJECT_ROOT = File.expand_path('../..', __FILE__)
SRC_DIRS = [
# Helper Library
- 'lib/**/*.coffee',
+ 'examples_lib/**/*.coffee',
# Examples for individual libraries
'ex_backbone_articulation_js/**/*.coffee',
View
36 vendor/backbone-articulation.js
@@ -1,4 +1,4 @@
-// Backbone-Articulation.js 0.1.0
+// Backbone-Articulation.js 0.1.1
// (c) 2011 Kevin Malakoff.
// Backbone-Articulation may be freely distributed under the MIT license.
@@ -9,9 +9,10 @@ if (!Backbone.HAS_ATTRIBUTE_OWNERSHIP) alert("Please upgrade Backbone to a versi
// Requires Underscore.js and Underscore-Awesomer.js (_.parseJSON, _.keypathValueOwner, _.toJSON, _.own, and _.disown).
if (!_) alert("Missing Underscore.js");
if (!_.AWESOMENESS) alert("Missing Underscore-Awesomer.js");
+if (_.AWESOMENESS!=='1.0.1') alert("Underscore-Awesomer.js needs to be at version 1.0.1 or higher");
this.Backbone.Articulation || (Backbone.Articulation = {});
-Backbone.Articulation = '0.1.0';
+Backbone.Articulation = '0.1.1';
// Converts all of its models to plain old JSON (if needed) using _.toJSON.
Backbone.Collection.prototype.toJSON = function() {
@@ -27,31 +28,56 @@ Backbone.Collection.prototype.toJSON = function() {
Backbone.Collection.prototype.parse = function(resp, xhr) {
if (!resp || (!_.isArray(resp))) return resp;
var articulated_model_attributes = [];
+ var model_resp;
for (var i = 0, l = resp.length; i < l; i++) {
- articulated_model_attributes.push(_.parseJSON(resp[i], { properties: true }));
+ model_resp = resp[i];
+ if (model_resp.hasOwnProperty(_.PARSE_JSON_TYPE_FIELD)) {
+ model_resp = _.clone(model_resp);
+ delete model_resp[_.PARSE_JSON_TYPE_FIELD];
+ }
+ articulated_model_attributes.push(_.parseJSON(model_resp, { properties:true }));
}
+
return articulated_model_attributes;
};
// Converts a model attributes from objects to plain old JSON (if needed).
Backbone.Model.prototype.toJSON = function() {
- return _.toJSON(this.attributes, { properties:true });
+ var json = _.toJSON(this.attributes, { properties:true });
+
+ // ensure there is a type field
+ if (!json.hasOwnProperty(_.PARSE_JSON_TYPE_FIELD)) {
+ // use the type field
+ if (this.hasOwnProperty(_.PARSE_JSON_TYPE_FIELD)) {
+ json[_.PARSE_JSON_TYPE_FIELD] = this[_.PARSE_JSON_TYPE_FIELD];
+ }
+ // convert the class using an underscore and singularize convention
+ else if (String.prototype.underscore) {
+ json[_.PARSE_JSON_TYPE_FIELD] = _.classOf(this).underscore().singularize();
+ }
+ }
+
+ return json;
};
// Converts a model attributes from plain old JSON to objects (if needed).
Backbone.Model.prototype.parse = function(resp, xhr) {
if (!resp) return resp;
- return _.parseJSON(resp, { properties:true });
+ return _.parseJSON(resp, { properties:true, skip_type:true });
};
// Uses _.own to clone(), retain(), or just stores a reference to an articulated attribute object (if needed).
Backbone.Model.prototype._ownAttribute = function(key, value) {
if (!value) return;
+ if ((value instanceof Backbone.Model) || (value instanceof Backbone.Collection)) return value; // Backbone.Model has incompatible destroy (DELETE on server)
+ if (_.isArray(value) && value.length && ((value[0] instanceof Backbone.Model) || (value[0] instanceof Backbone.Collection))) return value; // Backbone.Model has incompatible destroy (DELETE on server)
return _.own(value);
};
// Uses _.disown to destroy() or release() to an attribute object (if needed).
Backbone.Model.prototype._disownAttribute = function(key, value) {
if (!value) return;
+ if ((value instanceof Backbone.Model) || (value instanceof Backbone.Collection)) return value; // Backbone.Model has incompatible destroy (DELETE on server)
+ if (_.isArray(value) && value.length && ((value[0] instanceof Backbone.Model) || (value[0] instanceof Backbone.Collection))) return value; // Backbone.Model has incompatible destroy (DELETE on server)
return _.disown(value);
};
View
242 vendor/mixin.js
@@ -24,7 +24,7 @@ var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments)
};
this.Mixin || (this.Mixin = {});
this.Mixin.Core || (this.Mixin.Core = {});
-Mixin.VERSION = '0.1.0';
+Mixin.VERSION = '0.1.1';
_ || (_ = {});
if (!_.isArray) {
_.isArray = function(obj) {
@@ -77,6 +77,18 @@ if (!_.size) {
return i;
};
}
+if (!_.find) {
+ _.find = function(obj, iter) {
+ var item, _i, _len;
+ for (_i = 0, _len = obj.length; _i < _len; _i++) {
+ item = obj[_i];
+ if (iter(item)) {
+ return item;
+ }
+ }
+ return null;
+ };
+}
Mixin.Core._Validate = (function() {
function _Validate() {}
_Validate.mixinInfo = function(mixin_info, overwrite, mixin_and_function) {
@@ -216,7 +228,7 @@ Mixin.Core._InstanceRecord = (function() {
throw new Error('Mixin: non-empty instance record being destroyed');
}
if (this.backbone_destroy_fn) {
- this.mix_target.bind('destroy', this.backbone_destroy_fn);
+ this.mix_target.unbind('destroy', this.backbone_destroy_fn);
this.backbone_destroy_fn = null;
}
return this.mix_target = null;
@@ -300,7 +312,8 @@ Mixin.Core._InstanceRecord = (function() {
return _InstanceRecord;
})();
Mixin.Core._ClassRecord = (function() {
- function _ClassRecord() {
+ function _ClassRecord(constructor) {
+ this.constructor = constructor;
this.mixins = {};
this.instance_records = [];
}
@@ -457,23 +470,23 @@ Mixin.Core._Manager = (function() {
return mix_target;
};
_Manager.mixout = function(mix_target, mixin_name_or_names) {
- var constructor, parameter, _doMixout, _i, _len, _ref;
+ var class_record, parameter, _doMixout, _i, _j, _len, _len2, _ref, _ref2;
if (Mixin.DEBUG) {
- Mixin.Core._Validate.instance(mix_target, 'Mixin.mixin', 'mix_target');
+ Mixin.Core._Validate.instance(mix_target, 'Mixin.mixout', 'mix_target');
}
_doMixout = __bind(function(mix_target, mixin_name) {
- var constructor;
+ var class_record, _i, _len, _ref;
if (Mixin.DEBUG) {
- Mixin.Core._Validate.string(mixin_name, 'Mixin.mixin.mixout', 'mixin_name');
+ Mixin.Core._Validate.string(mixin_name, 'Mixin.mixout', 'mixin_name');
}
- constructor = mix_target.constructor;
- while (constructor) {
- if (constructor._mixin_class_record) {
- if (constructor._mixin_class_record.destroyInstance(mix_target, mixin_name)) {
+ if (mix_target.constructor._mixin_class_records) {
+ _ref = mix_target.constructor._mixin_class_records;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ class_record = _ref[_i];
+ if (class_record.destroyInstance(mix_target, mixin_name)) {
return mix_target;
}
}
- constructor = constructor.__super__ && (constructor.__super__.constructor !== constructor) ? constructor.__super__.constructor : void 0;
}
return mix_target;
}, this);
@@ -484,14 +497,14 @@ Mixin.Core._Manager = (function() {
_doMixout(mix_target, parameter);
}
} else {
- constructor = mix_target.constructor;
- while (constructor) {
- if (constructor._mixin_class_record) {
- if (constructor._mixin_class_record.destroyInstance(mix_target)) {
+ if (mix_target.constructor._mixin_class_records) {
+ _ref2 = mix_target.constructor._mixin_class_records;
+ for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
+ class_record = _ref2[_j];
+ if (class_record.destroyInstance(mix_target)) {
return mix_target;
}
}
- constructor = constructor.__super__ && (constructor.__super__.constructor !== constructor) ? constructor.__super__.constructor : void 0;
}
}
return mix_target;
@@ -515,7 +528,7 @@ Mixin.Core._Manager = (function() {
if (_Manager.hasInstanceData(mix_target, mixin_name)) {
return true;
}
- class_record = _Manager._findClassRecord(mix_target.constructor, mixin_name);
+ class_record = _Manager._findClassRecord(mix_target, mixin_name);
if (!class_record) {
return false;
}
@@ -523,47 +536,84 @@ Mixin.Core._Manager = (function() {
}
};
_Manager.mixins = function(mix_target) {
- var constructor, mixins;
+ var class_record, mixins, _i, _len, _ref;
if (Mixin.DEBUG) {
Mixin.Core._Validate.instance(mix_target, mixins, 'Mixin.mixins', 'mix_target');
}
mixins = [];
- constructor = mix_target.constructor;
- while (constructor) {
- if (constructor._mixin_class_record) {
- constructor._mixin_class_record.collectMixinsForInstance(mixins, mix_target);
+ if (mix_target.constructor._mixin_class_records) {
+ _ref = mix_target.constructor._mixin_class_records;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ class_record = _ref[_i];
+ class_record.collectMixinsForInstance(mixins, mix_target);
}
- constructor = constructor.__super__ && (constructor.__super__.constructor !== constructor) ? constructor.__super__.constructor : void 0;
}
return mixins;
};
- _Manager.classHasMixin = function(constructor, mixin_name) {
- if (Mixin.DEBUG) {
- Mixin.Core._Validate.classConstructorAndMixinName(constructor, mixin_name, 'classHasMixin');
- }
- return !!_Manager._findClassRecord(constructor, mixin_name);
- };
- _Manager._findClassRecord = function(constructor, mixin_name) {
+ _Manager._getClassRecords = function(mix_target) {
+ var class_record, class_records, constructor, _i, _len, _ref;
+ class_records = [];
+ constructor = mix_target.constructor;
while (constructor) {
- if (constructor._mixin_class_record && constructor._mixin_class_record.classHasMixin(mixin_name)) {
- return constructor._mixin_class_record;
+ if (constructor._mixin_class_records) {
+ _ref = constructor._mixin_class_records;
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ class_record = _ref[_i];
+ if (mix_target instanceof class_record.constructor) {
+ class_records.push(class_record);
+ }
+ }
}
constructor = constructor.__super__ && (constructor.__super__.constructor !== constructor) ? constructor.__super__.constructor : void 0;
}
+ return class_records;
+ };
+ _Manager._findClassRecord = function(mix_target, mixin_name) {
+ var class_record, class_records, _i, _len;
+ class_records = this._getClassRecords(mix_target);
+ for (_i = 0, _len = class_records.length; _i < _len; _i++) {
+ class_record = class_records[_i];
+ if (class_record.classHasMixin(mixin_name)) {
+ return class_record;
+ }
+ }
};
_Manager._findOrCreateClassRecord = function(mix_target, mixin_info) {
- var class_record;
- class_record = _Manager._findClassRecord(mix_target.constructor, mixin_info.mixin_name);
+ var class_record, i, l, other_class_record, was_added;
+ class_record = _Manager._findClassRecord(mix_target, mixin_info.mixin_name);
if (class_record) {
return class_record;
}
- if (!mix_target.constructor._mixin_class_record) {
- mix_target.constructor._mixin_class_record = new Mixin.Core._ClassRecord();
+ if (mix_target.constructor._mixin_class_records) {
+ class_record = _.find(mix_target.constructor._mixin_class_records, function(test) {
+ return test.constructor === mix_target.constructor;
+ });
+ }
+ if (!class_record) {
+ class_record = new Mixin.Core._ClassRecord(mix_target.constructor);
+ if (mix_target.constructor._mixin_class_records) {
+ was_added = false;
+ i = 0;
+ l = mix_target.constructor._mixin_class_records.length;
+ while (i < l) {
+ other_class_record = mix_target.constructor._mixin_class_records[i];
+ if (mix_target instanceof other_class_record.constructor) {
+ mix_target.constructor._mixin_class_records.splice(i, 0, class_record);
+ was_added = true;
+ break;
+ }
+ i++;
+ }
+ if (!was_added) {
+ mix_target.constructor._mixin_class_records.push(class_record);
+ }
+ } else {
+ mix_target.constructor._mixin_class_records = [class_record];
+ }
if (Mixin._statistics) {
- Mixin._statistics.addConstructor(mix_target.constructor);
+ Mixin._statistics.addClassRecord(class_record);
}
}
- class_record = mix_target.constructor._mixin_class_record;
return class_record;
};
_Manager.hasInstanceData = function(mix_target, mixin_name) {
@@ -617,7 +667,6 @@ Mixin.hasMixin = Mixin.exists = Mixin.Core._Manager.hasMixin;
Mixin.mixins = Mixin.Core._Manager.mixins;
Mixin.hasInstanceData = Mixin.hasID = Mixin.Core._Manager.hasInstanceData;
Mixin.instanceData = Mixin.iD = Mixin.Core._Manager.instanceData;
-Mixin.classHasMixin = Mixin.Core._Manager.classHasMixin;
if (typeof exports !== 'undefined') {
exports.Mixin = Mixin;
}
@@ -628,9 +677,7 @@ if (typeof exports !== 'undefined') {
See the following for full license details:
https://github.com/kmalakoff/mixin/blob/master/LICENSE
Dependencies: Mixin.Core
-*/
-var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
-if (!Mixin && (typeof exports !== 'undefined')) {
+*/if (!Mixin && (typeof exports !== 'undefined')) {
this.Mixin = require('mixin_core').Mixin;
}
if (!Mixin) {
@@ -641,13 +688,13 @@ if (this.Mixin.STATISTICS === void 0) {
}
Mixin.Core.Statistics = (function() {
function Statistics() {
- this.constructors = [];
+ this.class_records = [];
}
- Statistics.prototype.addConstructor = function(constructor) {
- return this.constructors.push(constructor);
+ Statistics.prototype.addClassRecord = function(class_record) {
+ return this.class_records.push(class_record);
};
Statistics.prototype.purge = function() {
- this.constructors = [];
+ this.class_records = [];
return this.clear();
};
Statistics.prototype.clear = function() {
@@ -666,89 +713,68 @@ Mixin.Core.Statistics = (function() {
return this.byConstructor_getInstances();
};
Statistics.prototype.byInstance_getMixins = function() {
- var constructor, _i, _len, _ref;
+ var class_record, _i, _len, _ref;
if (!this.by_instance_get_mixins) {
this.by_instance_get_mixins = [];
- _ref = this.constructors;
+ _ref = this.class_records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- constructor = _ref[_i];
- this.constructorIterateClassRecords(constructor, __bind(function() {
- return this.constructorGetMixinsByInstance(constructor, this.by_instance_get_mixins);
- }, this));
+ class_record = _ref[_i];
+ this.classRecordGetMixinsByInstance(class_record, this.by_instance_get_mixins);
}
}
return this.by_instance_get_mixins;
};
Statistics.prototype.byInstance_withData = function() {
- var constructor, _i, _len, _ref;
+ var class_record, _i, _len, _ref;
if (!this.by_instance_with_data) {
this.by_instance_with_data = [];
- _ref = this.constructors;
+ _ref = this.class_records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- constructor = _ref[_i];
- this.constructorIterateClassRecords(constructor, __bind(function() {
- return this.constructorGetInstancesWithData(constructor, this.by_instance_with_data);
- }, this));
+ class_record = _ref[_i];
+ this.classRecordGetInstancesWithData(class_record, this.by_instance_with_data);
}
}
return this.by_instance_with_data;
};
Statistics.prototype.byMixin_getInstances = function() {
- var constructor, _i, _len, _ref;
+ var class_record, _i, _len, _ref;
if (!this.by_mixin_get_instances) {
this.by_mixin_get_instances = {};
- _ref = this.constructors;
+ _ref = this.class_records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- constructor = _ref[_i];
- this.constructorIterateClassRecords(constructor, __bind(function() {
- return this.constructorGetInstancesByMixin(constructor, this.by_mixin_get_instances);
- }, this));
+ class_record = _ref[_i];
+ this.classRecordGetInstancesByMixin(class_record, this.by_mixin_get_instances);
}
}
return this.by_mixin_get_instances;
};
Statistics.prototype.byMixin_getConstructors = function() {
- var constructor, _i, _len, _ref;
+ var class_record, _i, _len, _ref;
if (!this.by_mixin_get_constructors) {
this.by_mixin_get_constructors = {};
- _ref = this.constructors;
+ _ref = this.class_records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- constructor = _ref[_i];
- this.constructorIterateClassRecords(constructor, __bind(function() {
- return this.constructorGetMixins(constructor, this.by_mixin_get_constructors);
- }, this));
+ class_record = _ref[_i];
+ this.classRecordGetMixins(class_record, this.by_mixin_get_constructors);
}
}
return this.by_mixin_get_constructors;
};
Statistics.prototype.byConstructor_getInstances = function() {
- var constructor, _i, _len, _ref;
+ var class_record, _i, _len, _ref;
if (!this.by_constructor_get_instances) {
this.by_constructor_get_instances = {};
- _ref = this.constructors;
+ _ref = this.class_records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- constructor = _ref[_i];
- this.constructorIterateClassRecords(constructor, __bind(function() {
- return this.constructorGroupInstances(constructor, this.by_constructor_get_instances);
- }, this));
+ class_record = _ref[_i];
+ this.classRecordGroupInstances(class_record, this.by_constructor_get_instances);
}
}
return this.by_constructor_get_instances;
};
- Statistics.prototype.constructorIterateClassRecords = function(constructor, fn) {
- var _results;
- _results = [];
- while (constructor) {
- if (constructor._mixin_class_record) {
- fn(constructor);
- }
- _results.push(constructor = constructor.__super__ && (constructor.__super__.constructor !== constructor) ? constructor.__super__.constructor : void 0);
- }
- return _results;
- };
- Statistics.prototype.constructorGetInstancesWithData = function(constructor, instances) {
+ Statistics.prototype.classRecordGetInstancesWithData = function(class_record, instances) {
var instance_record, _i, _len, _ref, _results;
- _ref = constructor._mixin_class_record.instance_records;
+ _ref = class_record.instance_records;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
instance_record = _ref[_i];
@@ -756,12 +782,12 @@ Mixin.Core.Statistics = (function() {
}
return _results;
};
- Statistics.prototype.constructorGetInstancesByMixin = function(constructor, mixins) {
+ Statistics.prototype.classRecordGetInstancesByMixin = function(class_record, mixins) {
var instance_record, key, mixin_info, _i, _len, _ref, _results;
- if (!constructor._mixin_class_record.instance_records.length) {
+ if (!class_record.instance_records.length) {
return;
}
- _ref = constructor._mixin_class_record.instance_records;
+ _ref = class_record.instance_records;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
instance_record = _ref[_i];
@@ -778,9 +804,9 @@ Mixin.Core.Statistics = (function() {
}
return _results;
};
- Statistics.prototype.constructorGetMixinsByInstance = function(constructor, instances) {
+ Statistics.prototype.classRecordGetMixinsByInstance = function(class_record, instances) {
var instance_record, _i, _len, _ref, _results;
- _ref = constructor._mixin_class_record.instance_records;
+ _ref = class_record.instance_records;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
instance_record = _ref[_i];
@@ -800,29 +826,29 @@ Mixin.Core.Statistics = (function() {
}
return _results;
};
- Statistics.prototype.constructorGroupInstances = function(constructor, constructors) {
+ Statistics.prototype.classRecordGroupInstances = function(class_record, constructors) {
var instance_record, _i, _len, _ref, _results;
- if (!constructor._mixin_class_record.instance_records.length) {
+ if (!class_record.instance_records.length) {
return;
}
- if (!constructors.hasOwnProperty(constructor.name)) {
- constructors[constructor] = [];
+ if (!constructors.hasOwnProperty(class_record.constructor.name)) {
+ constructors[class_record.constructor] = [];
}
- _ref = constructor._mixin_class_record.instance_records;
+ _ref = class_record.instance_records;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
instance_record = _ref[_i];
- _results.push(constructors[constructor].push(instance_record.mix_target));
+ _results.push(constructors[class_record.constructor].push(instance_record.mix_target));
}
return _results;
};
- Statistics.prototype.constructorGetMixins = function(constructor, mixins, only_with_instances) {
+ Statistics.prototype.classRecordGetMixins = function(class_record, mixins, only_with_instances) {
var key, mixin_info, _ref, _results;
- _ref = constructor._mixin_class_record.mixins;
+ _ref = class_record.mixins;
_results = [];
for (key in _ref) {
mixin_info = _ref[key];
- _results.push((!mixins.hasOwnProperty(key) ? mixins[key] = [] : void 0, mixins[key].push(constructor)));
+ _results.push((!mixins.hasOwnProperty(key) ? mixins[key] = [] : void 0, mixins[key].push(class_record.constructor)));
}
return _results;
};
@@ -1069,11 +1095,15 @@ Mixin.AutoMemory.Property = (function() {
}
};
Property.prototype._destroyEntry = function(entry) {
- var fn_ref, key, property, value, _i, _len, _ref;
+ var fn_ref, key, keypath_owner, property, value, _i, _len, _ref;
key = entry[0];
fn_ref = entry.length > 1 ? entry[1] : void 0;
if (!fn_ref) {
- _.keypath(this.owner, key, null);
+ keypath_owner = _.keypathValueOwner(this.owner, key);
+ if (!keypath_owner) {
+ throw new Error("Mixin.AutoMemory: property '" + key + "' doesn't exist on '" + (_.classOf(this.owner)) + "'");
+ }
+ keypath_owner[key] = null;
return;
}
value = _.keypath(this.owner, key);
View
194 vendor/underscore-awesomer.js
@@ -1,4 +1,4 @@
-// Underscore-Awesomer.js 1.0.0
+// Underscore-Awesomer.js 1.0.1
// (c) 2011 Kevin Malakoff.
// Underscore-Awesomer is freely distributable under the MIT license.
// Underscore-Awesomer are extensions to the Underscore library: http://documentcloud.github.com/underscore
@@ -24,7 +24,7 @@
var _ = root._;
// Dude, the current version is awesome!
- _.AWESOMENESS = '1.0.0';
+ _.AWESOMENESS = '1.0.1';
// Modifications to Underscore
// --------------------
@@ -36,105 +36,6 @@
_.map(obj, function(value){ return value[key]; });
};
- // Internal recursive comparison function.
- function eq(a, b, stack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
- if (a === b) return a !== 0 || 1 / a == 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if ((a == null) || (b == null)) return a === b;
- // Unwrap any wrapped objects.
- if (a._chain) a = a._wrapped;
- if (b._chain) b = b._wrapped;
- // Invoke a custom `isEqual` method if one is provided.
- if (_.isFunction(a.isEqual)) return a.isEqual(b);
- if (_.isFunction(b.isEqual)) return b.isEqual(a);
- // Compare object types.
- var typeA = typeof a;
- if (typeA != typeof b) return false;
- // Optimization; ensure that both values are truthy or falsy.
- if (!a != !b) return false;
- // `NaN` values are equal.
- if (_.isNaN(a)) return _.isNaN(b);
- // Compare string objects by value.
- var isStringA = _.isString(a), isStringB = _.isString(b);
- if (isStringA || isStringB) return isStringA && isStringB && String(a) == String(b);
- // Compare number objects by value.
- var isNumberA = _.isNumber(a), isNumberB = _.isNumber(b);
- if (isNumberA || isNumberB) return isNumberA && isNumberB && +a == +b;
- // Compare boolean objects by value. The value of `true` is 1; the value of `false` is 0.
- var isBooleanA = _.isBoolean(a), isBooleanB = _.isBoolean(b);
- if (isBooleanA || isBooleanB) return isBooleanA && isBooleanB && +a == +b;
- // Compare dates by their millisecond values.
- var isDateA = _.isDate(a), isDateB = _.isDate(b);
- if (isDateA || isDateB) return isDateA && isDateB && a.getTime() == b.getTime();
- // Compare RegExps by their source patterns and flags.
- var isRegExpA = _.isRegExp(a), isRegExpB = _.isRegExp(b);
- if (isRegExpA || isRegExpB) {
- // Ensure commutative equality for RegExps.
- return isRegExpA && isRegExpB &&
- a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- // Ensure that both values are objects.
- if (typeA != 'object') return false;
- // Assume equality for cyclic structures. The algorithm for detecting cyclic structures is
- // adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- var length = stack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of unique nested
- // structures.
- if (stack[length] == a) return true;
- }
- // Add the first object to the stack of traversed objects.
- stack.push(a);
- var size = 0, result = true;
- if (a.length === +a.length || b.length === +b.length) {
- // Patch until solution is agreed: https://github.com/documentcloud/underscore/issues/329
- // Reduces false positives by forcing the objects to be the same type instead of strict array-like checks
- result = ((a instanceof b.constructor) || (b instanceof a.constructor));
- if (result) {
- // Compare object lengths to determine if a deep comparison is necessary.
- size = a.length;
- result = size == b.length;
- if (result) {
- // Deep compare array-like object contents, ignoring non-numeric properties.
- while (size--) {
- // Ensure commutative equality for sparse arrays.
- if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
- }
- }
- }
- } else {
- // Deep compare objects.
- for (var key in a) {
- if (hasOwnProperty.call(a, key)) {
- // Count the expected number of properties.
- size++;
- // Deep compare each member.
- if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
- }
- }
- // Ensure that both objects contain the same number of properties.
- if (result) {
- for (key in b) {
- if (hasOwnProperty.call(b, key) && !size--) break;
- }
- result = !size;
- }
- }
- // Remove the first object from the stack of traversed objects.
- stack.pop();
- return result;
- }
-
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- return eq(a, b, []);
- };
-
// Collection Functions
// --------------------
@@ -340,14 +241,35 @@
}
};
- // Create a duplicate of an object to any zero-indexed depth.
- _.cloneToDepth = function(obj, depth) {
- if (typeof obj !== 'object') return obj;
- if (_.isUndefined(depth)) depth = 0;
- if (depth < 1) return _.clone(obj);
- clone = _.clone(obj);
- for (var key in clone) {
- clone[key] = _.cloneToDepth(clone[key], depth-1);
+ // Create a duplicate of a container of objects to any zero-indexed depth.
+ _.cloneToDepth = _.containerClone = _.clone = function(obj, depth) {
+ if (!obj || (typeof obj !== 'object')) return obj; // by value
+ var clone;
+ if (_.isArray(obj)) clone = Array.prototype.slice.call(obj);
+ else if (obj.constructor!=={}.constructor) return obj; // by reference
+ else clone = _.extend({}, obj);
+ if (!_.isUndefined(depth) && (depth > 0)) {
+ for (var key in clone) {
+ clone[key] = _.clone(clone[key], depth-1);
+ }
+ }
+ return clone;
+ };
+
+ // Create a duplicate of all objects to any zero-indexed depth.
+ _.deepClone = function(obj, depth) {
+ if (!obj || (typeof obj !== 'object')) return obj; // by value
+ else if (_.isString(obj)) return String.prototype.slice.call(obj);
+ else if (_.isDate(obj)) return new Date(obj.valueOf());
+ else if (_.isFunction(obj.clone)) return obj.clone();
+ var clone;
+ if (_.isArray(obj)) clone = Array.prototype.slice.call(obj);
+ else if (obj.constructor!=={}.constructor) return obj; // by reference
+ else clone = _.extend({}, obj);
+ if (!_.isUndefined(depth) && (depth > 0)) {
+ for (var key in clone) {
+ clone[key] = _.deepClone(clone[key], depth-1);
+ }
}
return clone;
};
@@ -554,21 +476,23 @@
// <br/>**Options:**<br/>
// * `properties` - used to disambigate between owning an object and owning _.each property.<br/>
// * `clear_values` - used to disambigate between clearing disowned items and removing them (by default, they are removed).
+ // * `remove_values` - used to indicate that the values should be disowned and removed from the collections.
_.disown = function(obj, options) {
if (!obj || (typeof(obj)!='object')) return obj;
options || (options = {});
if (_.isArray(obj)) {
- if (options.clear_values) { _.each(obj, function(value, index) { _.disown(value); obj[index]=null; }); return obj; }
+ if (options.clear_values) { _.each(obj, function(value, index) { _.disown(value, {clear_values: options.clear_values}); obj[index]=null; }); return obj; }
else {
- _.each(obj, function(value) { _.disown(value); });
- obj.length=0; return obj;
+ _.each(obj, function(value) { _.disown(value, {remove_values: options.remove_values}); });
+ if (options.remove_values) {obj.length=0;}
+ return obj;
}
}
else if (options.properties) {
- if (options.clear_values) { _.each(obj, function(value, key) { _.disown(value); obj[key]=null; }); return obj; }
+ if (options.clear_values) { _.each(obj, function(value, key) { _.disown(value, {clear_values: options.clear_values}); obj[key]=null; }); return obj; }
else {
- _.each(obj, function(value) { _.disown(value); });
- for(key in obj) { delete obj[key]; }
+ _.each(obj, function(value) { _.disown(value, {remove_values: options.remove_values}); });
+ if (options.remove_values) {for(key in obj) { delete obj[key]; }}
return obj;
}
}
@@ -645,6 +569,7 @@
// <br/>**Options:**<br/>
//* `type_field` - the default is '\_type' but you can choose any field name to trigger the search for a parseJSON function.<br/>
//* `properties` - used to disambigate between owning a collection's items and cloning a collection.
+ //* `skip_type` - skip a type check. Useful for if your model is already deserialized and you want to deserialize your properties. See Backbone.Articulation for an example.
// <br/>**Global settings:**<br/>
//* `_.PARSE_JSON_TYPE_FIELD` - the field key in the serialized JSON that is used for constructor lookup.<br/>
//* `_.PARSE_JSON_CONSTRUCTOR_ROOTS` - the array of roots that are used to find the constructor. Useful for reducing global namespace pollution<br/>
@@ -670,26 +595,37 @@
return result;
}
- // Parse the properties individually
- else if(options && options.properties) {
- result = {};
- _.each(obj, function(value, key) { result[key] = _.parseJSON(value, type_field); });
- return result;
+ // Use the type field
+ options||(options={});
+ var type_field = (options.type_field) ? options.type_field : _.PARSE_JSON_TYPE_FIELD;
+ if (options.skip_type || !(obj instanceof Object) || !obj.hasOwnProperty(type_field)) {
+ // Parse the properties individually
+ if(options.properties) {
+ result = {};
+ _.each(obj, function(value, key) { result[key] = _.parseJSON(value, type_field); });
+ return result;
+ }
+ else return obj;
}
- // No deseralization available
- var type_field = (options && options.type_field) ? options.type_field : _.PARSE_JSON_TYPE_FIELD;
- if (!(obj instanceof Object) || !obj.hasOwnProperty(type_field)) return obj;
-
// Find and use the parseJSON function
var type = obj[type_field];
- var current_root;
+ var current_root, instance;
- // Try root.type Global namespace
+ // Try searching in the available namespaces
for (var i=0, l=_.PARSE_JSON_CONSTRUCTOR_ROOTS.length; i<l;i++) {
current_root = _.PARSE_JSON_CONSTRUCTOR_ROOTS[i];
- parseJSON_owner = _.keypathValueOwner(current_root, type+'.parseJSON');
- if (parseJSON_owner) return parseJSON_owner.parseJSON(obj);
+ constructor_or_root = _.keypath(current_root, type);
+ if (constructor_or_root) {
+ // class/root parse function
+ if (_.isFunction(constructor_or_root.parseJSON)) return constructor_or_root.parseJSON(obj);
+ // instance parse function (Backbone.Model and Backbone.Collection style)
+ else if (constructor_or_root.prototype && _.isFunction(constructor_or_root.prototype.parse)) {
+ instance = new constructor_or_root();
+ if (_.isFunction(instance.set)) return instance.set(instance.parse(obj));
+ else return instance.parse(obj);
+ }
+ }
}
throw new TypeError("Unable to find a parseJSON function for type: " + type);
@@ -702,7 +638,6 @@
// Modifications to Underscore
// --------------------
pluck: _.pluck,
- isEqual: _.isEqual,
// Collection Functions
// ----------------
@@ -719,6 +654,7 @@
keypathValueOwner: _.keypathValueOwner,
keypath: _.keypath,
cloneToDepth: _.cloneToDepth,
+ clone: _.clone,
isConstructor: _.isConstructor,
resolveConstructor: _.resolveConstructor,
View
301 vendor/underscore.js
@@ -1,4 +1,4 @@
-// Underscore.js 1.1.7
+// Underscore.js 1.2.1
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
@@ -48,19 +48,26 @@
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
- // Export the Underscore object for **CommonJS**, with backwards-compatibility
- // for the old `require()` API. If we're not in CommonJS, add `_` to the
- // global object.
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = _;
- _._ = _;
+ // Export the Underscore object for **Node.js** and **"CommonJS"**, with
+ // backwards-compatibility for the old `require()` API. If we're not in
+ // CommonJS, add `_` to the global object.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else if (typeof define === 'function' && define.amd) {
+ // Register as a named module with AMD.
+ define('underscore', function() {
+ return _;
+ });
} else {
// Exported as a string, for Closure Compiler "advanced" mode.
root['_'] = _;
}
// Current version.
- _.VERSION = '1.1.7';
+ _.VERSION = '1.2.1';
// Collection Functions
// --------------------
@@ -198,8 +205,8 @@
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
- any(obj, function(value) {
- if (found = value === target) return true;
+ found = any(obj, function(value) {
+ if (value === target) return true;
});
return found;
};
@@ -220,6 +227,7 @@
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
@@ -231,6 +239,7 @@
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
+ if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
@@ -239,6 +248,21 @@
return result.value;
};
+ // Shuffle an array.
+ _.shuffle = function(obj) {
+ var shuffled = [], rand;
+ each(obj, function(value, index, list) {
+ if (index == 0) {
+ shuffled[0] = value;
+ } else {
+ rand = Math.floor(Math.random() * (index + 1));
+ shuffled[index] = shuffled[rand];
+ shuffled[rand] = value;
+ }
+ });
+ return shuffled;
+ };
+
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
@@ -252,9 +276,11 @@
}), 'value');
};
- // Groups the object's values by a criterion produced by an iterator
- _.groupBy = function(obj, iterator) {
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = function(obj, val) {
var result = {};
+ var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
@@ -298,6 +324,20 @@
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
+ // Returns everything but the last entry of the array. Especcialy useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ return (n != null) && !guard ? slice.call(array, array.length - n) : array[array.length - 1];
+ };
+
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
@@ -306,20 +346,15 @@
return slice.call(array, (index == null) || guard ? 1 : index);
};
- // Get the last element of an array.
- _.last = function(array) {
- return array[array.length - 1];
- };
-
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
- _.flatten = function(array) {
+ _.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
- if (_.isArray(value)) return memo.concat(_.flatten(value));
+ if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
@@ -333,17 +368,23 @@
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
- _.uniq = _.unique = function(array, isSorted) {
- return _.reduce(array, function(memo, el, i) {
- if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
+ _.uniq = _.unique = function(array, isSorted, iterator) {
+ var initial = iterator ? _.map(array, iterator) : array;
+ var result = [];
+ _.reduce(initial, function(memo, el, i) {
+ if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
+ memo[memo.length] = el;
+ result[result.length] = array[i];
+ }
return memo;
}, []);
+ return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
- return _.uniq(_.flatten(arguments));
+ return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
@@ -391,7 +432,6 @@
return -1;
};
-
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
@@ -426,15 +466,25 @@
// Function (ahem) Functions
// ------------------
+ // Reusable constructor function for prototype setting.
+ var ctor = function(){};
+
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
- _.bind = function(func, obj) {
+ _.bind = function bind(func, context) {
+ var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- var args = slice.call(arguments, 2);
- return function() {
- return func.apply(obj, args.concat(slice.call(arguments)));
+ if (!_.isFunction(func)) throw new TypeError;
+ args = slice.call(arguments, 2);
+ return bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ ctor.prototype = func.prototype;
+ var self = new ctor;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (Object(result) === result) return result;
+ return self;
};
};
@@ -470,31 +520,39 @@
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
- // Internal function used to implement `_.throttle` and `_.debounce`.
- var limit = function(func, wait, debounce) {
- var timeout;
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time.
+ _.throttle = function(func, wait) {
+ var timeout, context, args, throttling, finishThrottle;
+ finishThrottle = _.debounce(function(){ throttling = false; }, wait);
return function() {
- var context = this, args = arguments;
+ context = this; args = arguments;
var throttler = function() {
timeout = null;
func.apply(context, args);
+ finishThrottle();
};
- if (debounce) clearTimeout(timeout);
- if (debounce || !timeout) timeout = setTimeout(throttler, wait);
+ if (!timeout) timeout = setTimeout(throttler, wait);
+ if (!throttling) func.apply(context, args);
+ if (finishThrottle) finishThrottle();
+ throttling = true;
};
};
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time.
- _.throttle = function(func, wait) {
- return limit(func, wait, false);
- };
-
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
- return limit(func, wait, true);
+ var timeout;
+ return function() {
+ var context = this, args = arguments;
+ var throttler = function() {
+ timeout = null;
+ func.apply(context, args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(throttler, wait);
+ };
};
// Returns a function that will be executed at most one time, no matter how
@@ -538,7 +596,6 @@
};
};
-
// Object Functions
// ----------------
@@ -588,6 +645,7 @@
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
@@ -599,47 +657,93 @@
return obj;
};
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- // Check object identity.
- if (a === b) return true;
- // Different types?
- var atype = typeof(a), btype = typeof(b);
- if (atype != btype) return false;
- // Basic equality test (watch out for coercions).
- if (a == b) return true;
- // One is falsy and the other truthy.
- if ((!a && b) || (a && !b)) return false;
+ // Internal recursive comparison function.
+ function eq(a, b, stack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if ((a == null) || (b == null)) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
- // One of them implements an isEqual()?
- if (a.isEqual) return a.isEqual(b);
- if (b.isEqual) return b.isEqual(a);
- // Check dates' integer values.
- if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
- // Both are NaN?
- if (_.isNaN(a) && _.isNaN(b)) return false;
- // Compare regular expressions.
- if (_.isRegExp(a) && _.isRegExp(b))
- return a.source === b.source &&
- a.global === b.global &&
- a.ignoreCase === b.ignoreCase &&
- a.multiline === b.multiline;
- // If a is not an object by this point, we can't handle it.
- if (atype !== 'object') return false;
- // Check for different array lengths before comparing contents.
- if (a.length && (a.length !== b.length)) return false;
- // Nothing else worked, deep compare the contents.
- var aKeys = _.keys(a), bKeys = _.keys(b);
- // Different object sizes?
- if (aKeys.length != bKeys.length) return false;
- // Recursive comparison of contents.
- for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
- return true;
+ // Invoke a custom `isEqual` method if one is provided.
+ if (_.isFunction(a.isEqual)) return a.isEqual(b);
+ if (_.isFunction(b.isEqual)) return b.isEqual(a);
+ // Compare object types.
+ var typeA = typeof a;
+ if (typeA != typeof b) return false;
+ // Optimization; ensure that both values are truthy or falsy.
+ if (!a != !b) return false;
+ // `NaN` values are equal.
+ if (_.isNaN(a)) return _.isNaN(b);
+ // Compare string objects by value.
+ var isStringA = _.isString(a), isStringB = _.isString(b);
+ if (isStringA || isStringB) return isStringA && isStringB && String(a) == String(b);
+ // Compare number objects by value.
+ var isNumberA = _.isNumber(a), isNumberB = _.isNumber(b);
+ if (isNumberA || isNumberB) return isNumberA && isNumberB && +a == +b;
+ // Compare boolean objects by value. The value of `true` is 1; the value of `false` is 0.
+ var isBooleanA = _.isBoolean(a), isBooleanB = _.isBoolean(b);
+ if (isBooleanA || isBooleanB) return isBooleanA && isBooleanB && +a == +b;
+ // Compare dates by their millisecond values.
+ var isDateA = _.isDate(a), isDateB = _.isDate(b);
+ if (isDateA || isDateB) return isDateA && isDateB && a.getTime() == b.getTime();
+ // Compare RegExps by their source patterns and flags.
+ var isRegExpA = _.isRegExp(a), isRegExpB = _.isRegExp(b);
+ if (isRegExpA || isRegExpB) {
+ // Ensure commutative equality for RegExps.
+ return isRegExpA && isRegExpB &&
+ a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ // Ensure that both values are objects.
+ if (typeA != 'object') return false;
+ // Arrays or Arraylikes with different lengths are not equal.
+ if (a.length !== b.length) return false;
+ // Objects with different constructors are not equal.
+ if (a.constructor !== b.constructor) return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = stack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (stack[length] == a) return true;
+ }
+ // Add the first object to the stack of traversed objects.
+ stack.push(a);
+ var size = 0, result = true;
+ // Deep compare objects.
+ for (var key in a) {
+ if (hasOwnProperty.call(a, key)) {
+ // Count the expected number of properties.
+ size++;
+ // Deep compare each member.
+ if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
+ }
+ }
+ // Ensure that both objects contain the same number of properties.
+ if (result) {
+ for (key in b) {
+ if (hasOwnProperty.call(b, key) && !size--) break;
+ }
+ result = !size;
+ }
+ // Remove the first object from the stack of traversed objects.
+ stack.pop();
+ return result;
+ }
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, []);
};
- // Is a given array or object empty?
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
@@ -654,7 +758,7 @@
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) === '[object Array]';
+ return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
@@ -663,44 +767,50 @@
};
// Is a given variable an arguments object?
- _.isArguments = function(obj) {
- return !!(obj && hasOwnProperty.call(obj, 'callee'));
- };
+ if (toString.call(arguments) == '[object Arguments]') {
+ _.isArguments = function(obj) {
+ return toString.call(obj) == '[object Arguments]';
+ };
+ } else {
+ _.isArguments = function(obj) {
+ return !!(obj && hasOwnProperty.call(obj, 'callee'));
+ };
+ }
// Is a given value a function?
_.isFunction = function(obj) {
- return !!(obj && obj.constructor && obj.call && obj.apply);
+ return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
- return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
+ return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
- return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
+ return toString.call(obj) == '[object Number]';
};
- // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
- // that does not equal itself.
+ // Is the given value `NaN`?
_.isNaN = function(obj) {
+ // `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
- return obj === true || obj === false;
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value a date?
_.isDate = function(obj) {
- return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
+ return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
- return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
+ return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
@@ -733,6 +843,11 @@
for (var i = 0; i < n; i++) iterator.call(context, i);
};
+ // Escape a string for HTML interpolation.
+ _.escape = function(string) {
+ return (''+string).replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
+ };
+
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
@@ -753,7 +868,8 @@
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
};
// JavaScript micro-templating, similar to John Resig's implementation.
@@ -765,6 +881,9 @@
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
+ .replace(c.escape, function(match, code) {
+ return "',_.escape(" + code.replace(/\\'/g, "'") + "),'";
+ })
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
Please sign in to comment.
Something went wrong with that request. Please try again.