From faa776a67cdaa674fd8da596f62e8028f371e2c9 Mon Sep 17 00:00:00 2001 From: Adam Krebs Date: Fri, 28 Dec 2012 01:42:20 -0500 Subject: [PATCH] Add keys, values, pairs, invert, pick, omit, each, and other underscore methods to models --- backbone.js | 14 ++++++++++++++ test/model.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/backbone.js b/backbone.js index 4e116dec..55bb8214 100644 --- a/backbone.js +++ b/backbone.js @@ -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 // ------------------- diff --git a/test/model.js b/test/model.js index 8b8fe710..4c0143da 100644 --- a/test/model.js +++ b/test/model.js @@ -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();