Add keys, values, pairs, invert, pick, omit, each, and other

underscore methods to models
This commit is contained in:
Adam Krebs
2012-12-28 01:42:20 -05:00
parent 10cf99a7e6
commit faa776a67c
2 changed files with 45 additions and 0 deletions

View File

@@ -544,6 +544,20 @@
});
// Underscore methods that we want to implement on the Model.
var methods = ['each', 'forEach', 'map', 'collect', 'contains', 'include',
'sortBy', 'groupBy', 'size', 'keys', 'values', 'pairs', 'invert', 'pick',
'omit', 'isEqual', 'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(methods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------

View File

@@ -111,6 +111,37 @@ $(document).ready(function() {
equal(model.url(), '/nested/1/collection/2');
});
test("underscore methods", 19, function() {
var model = new Backbone.Model({ 'foo': 'a', 'bar': 'b', 'baz': 'c' });
var model2 = model.clone();
deepEqual(model.keys(), ['foo', 'bar', 'baz']);
deepEqual(model.values(), ['a', 'b', 'c']);
deepEqual(model.pairs(), [['foo', 'a'], ['bar', 'b'], ['baz', 'c']]);
deepEqual(model.invert(), { 'a': 'foo', 'b': 'bar', 'c': 'baz' });
deepEqual(model.pick('foo', 'baz'), {'foo': 'a', 'baz': 'c'});
deepEqual(model.omit('foo', 'bar'), {'baz': 'c'});
model.each(function(attr, index, attrs) {
ok(true);
});
equal(model.isEqual(model2.attributes), true);
equal(model.isEqual({ 'foo': 'a', 'bop': 'd' }), false);
equal(model.isEmpty(), false);
equal(model.size(), 3);
equal(model.contains('foo'), false);
equal(model.contains('b'), true);
equal(model.chain().keys().contains('foo').value(), true);
deepEqual(model.sortBy(function(val) { return val === 'b' }), ["c", "a", "b"]);
deepEqual(model.groupBy(), {
'a': ['a'],
'b': ['b'],
'c': ['c']
});
var prefixed = model.map(function(val, key, attrs){
return 'book-' + key;
});
deepEqual(prefixed, ['book-foo', 'book-bar', 'book-baz']);
});
test("clone", 10, function() {
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
var b = a.clone();