From 53eb7cf5f0c071c7d51ccf0aa52ea50c74ad5b5d Mon Sep 17 00:00:00 2001 From: Michael Mior Date: Thu, 16 May 2013 07:40:46 -0400 Subject: [PATCH] Add model.find, findOrCreate with create: false --- backbone-relational.js | 16 ++++++++++++++++ test/tests.js | 9 +++++++++ 2 files changed, 25 insertions(+) diff --git a/backbone-relational.js b/backbone-relational.js index e26badbd..39ba7f37 100755 --- a/backbone-relational.js +++ b/backbone-relational.js @@ -1658,6 +1658,22 @@ } return model; + }, + + /** + * Find an instance of `this` type in 'Backbone.Relational.store'. + * - If `attributes` is a string or a number, `find` will just query the `store` and return a model if found. + * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.update` is `false`. + * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model. + * @param {Object} [options] + * @param {Boolean} [options.merge=true] + * @param {Boolean} [options.parse=false] + * @return {Backbone.RelationalModel} + */ + find: function( attributes, options ) { + options || ( options = {} ); + options.create = false; + return this.findOrCreate( attributes, options ); } }); _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore ); diff --git a/test/tests.js b/test/tests.js index 99addb21..08dd8feb 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1290,6 +1290,15 @@ $(document).ready(function() { equal( person1.get( 'name' ), 'dude' ); }); + test( "constructor.find", function() { + var personColl = Backbone.Relational.store.getCollection( person1 ), + origPersonCollSize = personColl.length; + + // Look for a non-existent person + person = Person.find( { id: 5001 } ); + ok( !person ); + }); + test( "change events in relation can use changedAttributes properly", function() { var scope = {}; Backbone.Relational.store.addModelScope( scope );