forked from emberjs-addons/sproutcore-datastore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
children_attribute.js
77 lines (60 loc) · 2.35 KB
/
children_attribute.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2010 Evin Grano
// Portions ©2008-2011 Apple Inc. All rights reserved.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal');
require('sproutcore-datastore/system/record');
require('sproutcore-datastore/attributes/record_attribute');
require('sproutcore-datastore/attributes/child_attribute');
require('sproutcore-datastore/system/child_array');
var get = SC.get, set = SC.set;
/** @class
ChildrenAttribute is a subclass of ChildAttribute and handles to-many
relationships for child records.
When setting ( `set()` ) the value of a toMany attribute, make sure
to pass in an array of SC.Record objects.
There are many ways you can configure a ChildrenAttribute:
contacts: SC.ChildrenAttribute.attr('SC.Child');
@extends SC.RecordAttribute
@since SproutCore 1.0
*/
SC.ChildrenAttribute = SC.ChildAttribute.extend(
/** @scope SC.ChildrenAttribute.prototype */ {
// ..........................................................
// LOW-LEVEL METHODS
//
/** @private - adapted for to many relationship */
toType: function(record, key, value) {
var attrKey = get(this, 'key') || key,
arrayKey = '__kidsArray__'+SC.guidFor(this),
ret = record[arrayKey],
recordType = get(this, 'typeClass'), rel;
// lazily create a ManyArray one time. after that always return the
// same object.
if (!ret) {
ret = SC.ChildArray.create({
record: record,
propertyName: attrKey,
defaultRecordType: recordType
});
record[arrayKey] = ret ; // save on record
rel = get(record, 'relationships');
if (!rel) set(record, 'relationships', rel = []);
rel.push(ret); // make sure we get notified of changes...
}
return ret;
},
// Default fromType is just returning itself
fromType: function(record, key, value){
var sk, store,
arrayKey = '__kidsArray__'+SC.guidFor(this),
ret = record[arrayKey];
if (record) {
record.writeAttribute(key, value);
if (ret) ret = ret.recordPropertyDidChange();
}
return ret;
}
});