ninjatronic/angular-kinvey — pull request #23 by ninjatronic (2013-12-12 11:59:50+00:00)
Title: Automatically detects deep-nested $kinvey objects and replace with references

### $reference Method

Starting with version 2.0.0 $kinvey provides a $reference method for creating references from Resource instances, and can automatically detect nested objects and replace them with references when serializing for save operations.

To get the reference of a resource instance:

```javascript
var badger = new $kinvey.Badger({_id: 'myId'});
var reference = badger.$reference();
```

**NB:** $reference will return undefined if the Resource instance has no _id.

### Automatic Reference Replacement

During serialization for a saving operation, the library will detect any nested Resource instances inside the serializing model and replace them with references. This implementation (`flatten` method in the code) uses the `$reference` instance level method both as a marker and reference provider.

```
$kinvey.alias('badger', 'Badger');
var badger = new Badger({_id: 'badgerId'});
var user = new $kinvey.User({
username: 'username',
password: 'password',
badger: badger
});
user.$signup();
```

In the above example, the user object would be serialized and sent to Kinvey as...

```json
{
"username": "username",
"password": "password",
"badger": {
"_type": "KinveyRef",
"_collection": "badger",
"_id:": "badgerId"
}
}
```