ember-data-latest.js 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176
  1. (function() {
  2. window.DS = Ember.Namespace.create({
  3. CURRENT_API_REVISION: 4
  4. });
  5. })();
  6. (function() {
  7. var get = Ember.get, set = Ember.set;
  8. /**
  9. A record array is an array that contains records of a certain type. The record
  10. array materializes records as needed when they are retrieved for the first
  11. time. You should not create record arrays yourself. Instead, an instance of
  12. DS.RecordArray or its subclasses will be returned by your application's store
  13. in response to queries.
  14. */
  15. DS.RecordArray = Ember.ArrayProxy.extend({
  16. /**
  17. The model type contained by this record array.
  18. @type DS.Model
  19. */
  20. type: null,
  21. // The array of client ids backing the record array. When a
  22. // record is requested from the record array, the record
  23. // for the client id at the same index is materialized, if
  24. // necessary, by the store.
  25. content: null,
  26. // The store that created this record array.
  27. store: null,
  28. objectAtContent: function(index) {
  29. var content = get(this, 'content'),
  30. clientId = content.objectAt(index),
  31. store = get(this, 'store');
  32. if (clientId !== undefined) {
  33. return store.findByClientId(get(this, 'type'), clientId);
  34. }
  35. }
  36. });
  37. })();
  38. (function() {
  39. var get = Ember.get;
  40. DS.FilteredRecordArray = DS.RecordArray.extend({
  41. filterFunction: null,
  42. replace: function() {
  43. var type = get(this, 'type').toString();
  44. throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
  45. },
  46. updateFilter: Ember.observer(function() {
  47. var store = get(this, 'store');
  48. store.updateRecordArrayFilter(this, get(this, 'type'), get(this, 'filterFunction'));
  49. }, 'filterFunction')
  50. });
  51. })();
  52. (function() {
  53. var get = Ember.get, set = Ember.set;
  54. DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({
  55. query: null,
  56. isLoaded: false,
  57. replace: function() {
  58. var type = get(this, 'type').toString();
  59. throw new Error("The result of a server query (on " + type + ") is immutable.");
  60. },
  61. load: function(array) {
  62. var store = get(this, 'store'), type = get(this, 'type');
  63. var clientIds = store.loadMany(type, array).clientIds;
  64. this.beginPropertyChanges();
  65. set(this, 'content', Ember.A(clientIds));
  66. set(this, 'isLoaded', true);
  67. this.endPropertyChanges();
  68. }
  69. });
  70. })();
  71. (function() {
  72. var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor;
  73. var Set = function() {
  74. this.hash = {};
  75. this.list = [];
  76. };
  77. Set.prototype = {
  78. add: function(item) {
  79. var hash = this.hash,
  80. guid = guidFor(item);
  81. if (hash.hasOwnProperty(guid)) { return; }
  82. hash[guid] = true;
  83. this.list.push(item);
  84. },
  85. remove: function(item) {
  86. var hash = this.hash,
  87. guid = guidFor(item);
  88. if (!hash.hasOwnProperty(guid)) { return; }
  89. delete hash[guid];
  90. var list = this.list,
  91. index = Ember.EnumerableUtils.indexOf(this, item);
  92. list.splice(index, 1);
  93. },
  94. isEmpty: function() {
  95. return this.list.length === 0;
  96. }
  97. };
  98. var LoadedState = Ember.State.extend({
  99. recordWasAdded: function(manager, record) {
  100. var dirty = manager.dirty, observer;
  101. dirty.add(record);
  102. observer = function() {
  103. if (!get(record, 'isDirty')) {
  104. record.removeObserver('isDirty', observer);
  105. manager.send('childWasSaved', record);
  106. }
  107. };
  108. record.addObserver('isDirty', observer);
  109. },
  110. recordWasRemoved: function(manager, record) {
  111. var dirty = manager.dirty, observer;
  112. dirty.add(record);
  113. observer = function() {
  114. record.removeObserver('isDirty', observer);
  115. if (!get(record, 'isDirty')) { manager.send('childWasSaved', record); }
  116. };
  117. record.addObserver('isDirty', observer);
  118. }
  119. });
  120. var states = {
  121. loading: Ember.State.create({
  122. isLoaded: false,
  123. isDirty: false,
  124. loadedRecords: function(manager, count) {
  125. manager.decrement(count);
  126. },
  127. becameLoaded: function(manager) {
  128. manager.transitionTo('clean');
  129. }
  130. }),
  131. clean: LoadedState.create({
  132. isLoaded: true,
  133. isDirty: false,
  134. recordWasAdded: function(manager, record) {
  135. this._super(manager, record);
  136. manager.goToState('dirty');
  137. },
  138. update: function(manager, clientIds) {
  139. var manyArray = manager.manyArray;
  140. set(manyArray, 'content', clientIds);
  141. }
  142. }),
  143. dirty: LoadedState.create({
  144. isLoaded: true,
  145. isDirty: true,
  146. childWasSaved: function(manager, child) {
  147. var dirty = manager.dirty;
  148. dirty.remove(child);
  149. if (dirty.isEmpty()) { manager.send('arrayBecameSaved'); }
  150. },
  151. arrayBecameSaved: function(manager) {
  152. manager.goToState('clean');
  153. }
  154. })
  155. };
  156. DS.ManyArrayStateManager = Ember.StateManager.extend({
  157. manyArray: null,
  158. initialState: 'loading',
  159. states: states,
  160. /**
  161. This number is used to keep track of the number of outstanding
  162. records that must be loaded before the array is considered
  163. loaded. As results stream in, this number is decremented until
  164. it becomes zero, at which case the `isLoaded` flag will be set
  165. to true
  166. */
  167. counter: 0,
  168. init: function() {
  169. this._super();
  170. this.dirty = new Set();
  171. this.counter = get(this, 'manyArray.length');
  172. },
  173. decrement: function(count) {
  174. var counter = this.counter = this.counter - count;
  175. Ember.assert("Somehow the ManyArray loaded counter went below 0. This is probably an ember-data bug. Please report it at https://github.com/emberjs/data/issues", counter >= 0);
  176. if (counter === 0) {
  177. this.send('becameLoaded');
  178. }
  179. }
  180. });
  181. })();
  182. (function() {
  183. var get = Ember.get, set = Ember.set;
  184. DS.ManyArray = DS.RecordArray.extend({
  185. init: function() {
  186. set(this, 'stateManager', DS.ManyArrayStateManager.create({ manyArray: this }));
  187. return this._super();
  188. },
  189. parentRecord: null,
  190. isDirty: Ember.computed(function() {
  191. return get(this, 'stateManager.currentState.isDirty');
  192. }).property('stateManager.currentState').cacheable(),
  193. isLoaded: Ember.computed(function() {
  194. return get(this, 'stateManager.currentState.isLoaded');
  195. }).property('stateManager.currentState').cacheable(),
  196. send: function(event, context) {
  197. this.get('stateManager').send(event, context);
  198. },
  199. fetch: function() {
  200. var clientIds = get(this, 'content'),
  201. store = get(this, 'store'),
  202. type = get(this, 'type');
  203. store.fetchUnloadedClientIds(type, clientIds);
  204. },
  205. // Overrides Ember.Array's replace method to implement
  206. replaceContent: function(index, removed, added) {
  207. var parentRecord = get(this, 'parentRecord');
  208. var pendingParent = parentRecord && !get(parentRecord, 'id');
  209. var stateManager = get(this, 'stateManager');
  210. // Map the array of record objects into an array of client ids.
  211. added = added.map(function(record) {
  212. Ember.assert("You can only add records of " + (get(this, 'type') && get(this, 'type').toString()) + " to this association.", !get(this, 'type') || (get(this, 'type') === record.constructor));
  213. // If the record to which this many array belongs does not yet
  214. // have an id, notify the newly-added record that it must wait
  215. // for the parent to receive an id before the child can be
  216. // saved.
  217. if (pendingParent) {
  218. record.send('waitingOn', parentRecord);
  219. }
  220. var oldParent = this.assignInverse(record, parentRecord);
  221. record.get('transaction')
  222. .relationshipBecameDirty(record, oldParent, parentRecord);
  223. stateManager.send('recordWasAdded', record);
  224. return record.get('clientId');
  225. }, this);
  226. var store = this.store;
  227. var len = index+removed, record;
  228. for (var i = index; i < len; i++) {
  229. // TODO: null out inverse FK
  230. record = this.objectAt(i);
  231. var oldParent = this.assignInverse(record, parentRecord, true);
  232. record.get('transaction')
  233. .relationshipBecameDirty(record, parentRecord, null);
  234. // If we put the child record into a pending state because
  235. // we were waiting on the parent record to get an id, we
  236. // can tell the child it no longer needs to wait.
  237. if (pendingParent) {
  238. record.send('doneWaitingOn', parentRecord);
  239. }
  240. stateManager.send('recordWasAdded', record);
  241. }
  242. this._super(index, removed, added);
  243. },
  244. assignInverse: function(record, parentRecord, remove) {
  245. var associationMap = get(record.constructor, 'associations'),
  246. possibleAssociations = associationMap.get(parentRecord.constructor),
  247. possible, actual, oldParent;
  248. if (!possibleAssociations) { return; }
  249. for (var i = 0, l = possibleAssociations.length; i < l; i++) {
  250. possible = possibleAssociations[i];
  251. if (possible.kind === 'belongsTo') {
  252. actual = possible;
  253. break;
  254. }
  255. }
  256. if (actual) {
  257. oldParent = get(record, actual.name);
  258. set(record, actual.name, remove ? null : parentRecord);
  259. return oldParent;
  260. }
  261. },
  262. // Create a child record within the parentRecord
  263. createRecord: function(hash, transaction) {
  264. var parentRecord = get(this, 'parentRecord'),
  265. store = get(parentRecord, 'store'),
  266. type = get(this, 'type'),
  267. record;
  268. transaction = transaction || get(parentRecord, 'transaction');
  269. record = store.createRecord.call(store, type, hash, transaction);
  270. this.pushObject(record);
  271. return record;
  272. }
  273. });
  274. })();
  275. (function() {
  276. })();
  277. (function() {
  278. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt,
  279. removeObject = Ember.EnumerableUtils.removeObject;
  280. /**
  281. A transaction allows you to collect multiple records into a unit of work
  282. that can be committed or rolled back as a group.
  283. For example, if a record has local modifications that have not yet
  284. been saved, calling `commit()` on its transaction will cause those
  285. modifications to be sent to the adapter to be saved. Calling
  286. `rollback()` on its transaction would cause all of the modifications to
  287. be discarded and the record to return to the last known state before
  288. changes were made.
  289. If a newly created record's transaction is rolled back, it will
  290. immediately transition to the deleted state.
  291. If you do not explicitly create a transaction, a record is assigned to
  292. an implicit transaction called the default transaction. In these cases,
  293. you can treat your application's instance of `DS.Store` as a transaction
  294. and call the `commit()` and `rollback()` methods on the store itself.
  295. Once a record has been successfully committed or rolled back, it will
  296. be moved back to the implicit transaction. Because it will now be in
  297. a clean state, it can be moved to a new transaction if you wish.
  298. ### Creating a Transaction
  299. To create a new transaction, call the `transaction()` method of your
  300. application's `DS.Store` instance:
  301. var transaction = App.store.transaction();
  302. This will return a new instance of `DS.Transaction` with no records
  303. yet assigned to it.
  304. ### Adding Existing Records
  305. Add records to a transaction using the `add()` method:
  306. record = App.store.find(Person, 1);
  307. transaction.add(record);
  308. Note that only records whose `isDirty` flag is `false` may be added
  309. to a transaction. Once modifications to a record have been made
  310. (its `isDirty` flag is `true`), it is not longer able to be added to
  311. a transaction.
  312. ### Creating New Records
  313. Because newly created records are dirty from the time they are created,
  314. and because dirty records can not be added to a transaction, you must
  315. use the `createRecord()` method to assign new records to a transaction.
  316. For example, instead of this:
  317. var transaction = store.transaction();
  318. var person = Person.createRecord({ name: "Steve" });
  319. // won't work because person is dirty
  320. transaction.add(person);
  321. Call `createRecord()` on the transaction directly:
  322. var transaction = store.transaction();
  323. transaction.createRecord(Person, { name: "Steve" });
  324. ### Asynchronous Commits
  325. Typically, all of the records in a transaction will be committed
  326. together. However, new records that have a dependency on other new
  327. records need to wait for their parent record to be saved and assigned an
  328. ID. In that case, the child record will continue to live in the
  329. transaction until its parent is saved, at which time the transaction will
  330. attempt to commit again.
  331. For this reason, you should not re-use transactions once you have committed
  332. them. Always make a new transaction and move the desired records to it before
  333. calling commit.
  334. */
  335. DS.Transaction = Ember.Object.extend({
  336. /**
  337. @private
  338. Creates the bucket data structure used to segregate records by
  339. type.
  340. */
  341. init: function() {
  342. set(this, 'buckets', {
  343. clean: Ember.Map.create(),
  344. created: Ember.Map.create(),
  345. updated: Ember.Map.create(),
  346. deleted: Ember.Map.create(),
  347. inflight: Ember.Map.create()
  348. });
  349. this.dirtyRelationships = {
  350. byChild: Ember.Map.create(),
  351. byNewParent: Ember.Map.create(),
  352. byOldParent: Ember.Map.create()
  353. };
  354. },
  355. /**
  356. Creates a new record of the given type and assigns it to the transaction
  357. on which the method was called.
  358. This is useful as only clean records can be added to a transaction and
  359. new records created using other methods immediately become dirty.
  360. @param {DS.Model} type the model type to create
  361. @param {Object} hash the data hash to assign the new record
  362. */
  363. createRecord: function(type, hash) {
  364. var store = get(this, 'store');
  365. return store.createRecord(type, hash, this);
  366. },
  367. /**
  368. Adds an existing record to this transaction. Only records without
  369. modficiations (i.e., records whose `isDirty` property is `false`)
  370. can be added to a transaction.
  371. @param {DS.Model} record the record to add to the transaction
  372. */
  373. add: function(record) {
  374. // we could probably make this work if someone has a valid use case. Do you?
  375. Ember.assert("Once a record has changed, you cannot move it into a different transaction", !get(record, 'isDirty'));
  376. var recordTransaction = get(record, 'transaction'),
  377. defaultTransaction = get(this, 'store.defaultTransaction');
  378. Ember.assert("Models cannot belong to more than one transaction at a time.", recordTransaction === defaultTransaction);
  379. this.adoptRecord(record);
  380. },
  381. /**
  382. Commits the transaction, which causes all of the modified records that
  383. belong to the transaction to be sent to the adapter to be saved.
  384. Once you call `commit()` on a transaction, you should not re-use it.
  385. When a record is saved, it will be removed from this transaction and
  386. moved back to the store's default transaction.
  387. */
  388. commit: function() {
  389. var self = this,
  390. iterate;
  391. iterate = function(bucketType, fn, binding) {
  392. var dirty = self.bucketForType(bucketType);
  393. dirty.forEach(function(type, records) {
  394. if (records.isEmpty()) { return; }
  395. var array = [];
  396. records.forEach(function(record) {
  397. record.send('willCommit');
  398. if (get(record, 'isPending') === false) {
  399. array.push(record);
  400. }
  401. });
  402. fn.call(binding, type, array);
  403. });
  404. };
  405. var commitDetails = {
  406. updated: {
  407. eachType: function(fn, binding) { iterate('updated', fn, binding); }
  408. },
  409. created: {
  410. eachType: function(fn, binding) { iterate('created', fn, binding); }
  411. },
  412. deleted: {
  413. eachType: function(fn, binding) { iterate('deleted', fn, binding); }
  414. }
  415. };
  416. var store = get(this, 'store');
  417. var adapter = get(store, '_adapter');
  418. this.removeCleanRecords();
  419. if (adapter && adapter.commit) { adapter.commit(store, commitDetails); }
  420. else { throw fmt("Adapter is either null or does not implement `commit` method", this); }
  421. },
  422. /**
  423. Rolling back a transaction resets the records that belong to
  424. that transaction.
  425. Updated records have their properties reset to the last known
  426. value from the persistence layer. Deleted records are reverted
  427. to a clean, non-deleted state. Newly created records immediately
  428. become deleted, and are not sent to the adapter to be persisted.
  429. After the transaction is rolled back, any records that belong
  430. to it will return to the store's default transaction, and the
  431. current transaction should not be used again.
  432. */
  433. rollback: function() {
  434. var store = get(this, 'store'),
  435. dirty;
  436. // Loop through all of the records in each of the dirty states
  437. // and initiate a rollback on them. As a side effect of telling
  438. // the record to roll back, it should also move itself out of
  439. // the dirty bucket and into the clean bucket.
  440. ['created', 'updated', 'deleted', 'inflight'].forEach(function(bucketType) {
  441. dirty = this.bucketForType(bucketType);
  442. dirty.forEach(function(type, records) {
  443. records.forEach(function(record) {
  444. record.send('rollback');
  445. });
  446. });
  447. }, this);
  448. // Now that all records in the transaction are guaranteed to be
  449. // clean, migrate them all to the store's default transaction.
  450. this.removeCleanRecords();
  451. },
  452. /**
  453. @private
  454. Removes a record from this transaction and back to the store's
  455. default transaction.
  456. Note: This method is private for now, but should probably be exposed
  457. in the future once we have stricter error checking (for example, in the
  458. case of the record being dirty).
  459. @param {DS.Model} record
  460. */
  461. remove: function(record) {
  462. var defaultTransaction = get(this, 'store.defaultTransaction');
  463. defaultTransaction.adoptRecord(record);
  464. },
  465. /**
  466. @private
  467. Removes all of the records in the transaction's clean bucket.
  468. */
  469. removeCleanRecords: function() {
  470. var clean = this.bucketForType('clean'),
  471. self = this;
  472. clean.forEach(function(type, records) {
  473. records.forEach(function(record) {
  474. self.remove(record);
  475. });
  476. });
  477. },
  478. /**
  479. @private
  480. Returns the bucket for the given bucket type. For example, you might call
  481. `this.bucketForType('updated')` to get the `Ember.Map` that contains all
  482. of the records that have changes pending.
  483. @param {String} bucketType the type of bucket
  484. @returns Ember.Map
  485. */
  486. bucketForType: function(bucketType) {
  487. var buckets = get(this, 'buckets');
  488. return get(buckets, bucketType);
  489. },
  490. /**
  491. @private
  492. This method moves a record into a different transaction without the normal
  493. checks that ensure that the user is not doing something weird, like moving
  494. a dirty record into a new transaction.
  495. It is designed for internal use, such as when we are moving a clean record
  496. into a new transaction when the transaction is committed.
  497. This method must not be called unless the record is clean.
  498. @param {DS.Model} record
  499. */
  500. adoptRecord: function(record) {
  501. var oldTransaction = get(record, 'transaction');
  502. if (oldTransaction) {
  503. oldTransaction.removeFromBucket('clean', record);
  504. }
  505. this.addToBucket('clean', record);
  506. set(record, 'transaction', this);
  507. },
  508. /**
  509. @private
  510. Adds a record to the named bucket.
  511. @param {String} bucketType one of `clean`, `created`, `updated`, or `deleted`
  512. */
  513. addToBucket: function(bucketType, record) {
  514. var bucket = this.bucketForType(bucketType),
  515. type = record.constructor;
  516. var records = bucket.get(type);
  517. if (!records) {
  518. records = Ember.OrderedSet.create();
  519. bucket.set(type, records);
  520. }
  521. records.add(record);
  522. },
  523. /**
  524. @private
  525. Removes a record from the named bucket.
  526. @param {String} bucketType one of `clean`, `created`, `updated`, or `deleted`
  527. */
  528. removeFromBucket: function(bucketType, record) {
  529. var bucket = this.bucketForType(bucketType),
  530. type = record.constructor;
  531. var records = bucket.get(type);
  532. records.remove(record);
  533. },
  534. /**
  535. @private
  536. Called by a ManyArray when a new record is added to it. This
  537. method will index a relationship description by the child
  538. record, its old parent, and its new parent.
  539. The store will provide this description to the adapter's
  540. shouldCommit method, so it can determine whether any of
  541. the records is pending another record. The store will also
  542. provide a list of these descriptions to the adapter's commit
  543. method.
  544. @param {DS.Model} record the new child record
  545. @param {DS.Model} oldParent the parent that the child is
  546. moving from, or null
  547. @param {DS.Model} newParent the parent that the child is
  548. moving to, or null
  549. */
  550. relationshipBecameDirty: function(child, oldParent, newParent) {
  551. var relationships = this.dirtyRelationships, relationship;
  552. var relationshipsForChild = relationships.byChild.get(child),
  553. possibleRelationship,
  554. needsNewEntries = true;
  555. // If the child has any existing dirty relationships in this
  556. // transaction, we need to collapse the old relationship
  557. // into the new one. For example, if we change the parent of
  558. // a child record before saving, there is no need to save the
  559. // record that was its parent temporarily.
  560. if (relationshipsForChild) {
  561. // Loop through all of the relationships we know about that
  562. // contain the same child as the new relationship.
  563. for (var i=0, l=relationshipsForChild.length; i<l; i++) {
  564. relationship = relationshipsForChild[i];
  565. // If the parent of the child record has changed, there is
  566. // no need to update the old parent that had not yet been saved.
  567. //
  568. // This case is two changes in a record's parent:
  569. //
  570. // A -> B
  571. // B -> C
  572. //
  573. // In this case, there is no need to remember the A->B
  574. // change. We can collapse both changes into:
  575. //
  576. // A -> C
  577. //
  578. // Another possible case is:
  579. //
  580. // A -> B
  581. // B -> A
  582. //
  583. // In this case, we don't need to do anything. We can
  584. // simply remove the original A->B change and call it
  585. // a day.
  586. if (relationship.newParent === oldParent) {
  587. oldParent = relationship.oldParent;
  588. this.removeRelationship(relationship);
  589. // This is the case of A->B followed by B->A.
  590. if (relationship.oldParent === newParent) {
  591. needsNewEntries = false;
  592. }
  593. }
  594. }
  595. }
  596. relationship = {
  597. child: child,
  598. oldParent: oldParent,
  599. newParent: newParent
  600. };
  601. // If we didn't go A->B and then B->A, add new dirty relationship
  602. // entries.
  603. if (needsNewEntries) {
  604. this.addRelationshipTo('byChild', child, relationship);
  605. this.addRelationshipTo('byOldParent', oldParent, relationship);
  606. this.addRelationshipTo('byNewParent', newParent, relationship);
  607. }
  608. },
  609. removeRelationship: function(relationship) {
  610. var relationships = this.dirtyRelationships;
  611. removeObject(relationships.byOldParent.get(relationship.oldParent), relationship);
  612. removeObject(relationships.byNewParent.get(relationship.newParent), relationship);
  613. removeObject(relationships.byChild.get(relationship.child), relationship);
  614. },
  615. addRelationshipTo: function(type, record, description) {
  616. var map = this.dirtyRelationships[type];
  617. var relationships = map.get(record);
  618. if (!relationships) {
  619. relationships = [ description ];
  620. map.set(record, relationships);
  621. } else {
  622. relationships.push(description);
  623. }
  624. },
  625. /**
  626. @private
  627. Called by a record's state manager to indicate that the record has entered
  628. a dirty state. The record will be moved from the `clean` bucket and into
  629. the appropriate dirty bucket.
  630. @param {String} bucketType one of `created`, `updated`, or `deleted`
  631. */
  632. recordBecameDirty: function(bucketType, record) {
  633. this.removeFromBucket('clean', record);
  634. this.addToBucket(bucketType, record);
  635. },
  636. /**
  637. @private
  638. Called by a record's state manager to indicate that the record has entered
  639. inflight state. The record will be moved from its current dirty bucket and into
  640. the `inflight` bucket.
  641. @param {String} bucketType one of `created`, `updated`, or `deleted`
  642. */
  643. recordBecameInFlight: function(kind, record) {
  644. this.removeFromBucket(kind, record);
  645. this.addToBucket('inflight', record);
  646. },
  647. /**
  648. @private
  649. Called by a record's state manager to indicate that the record has entered
  650. a clean state. The record will be moved from its current dirty or inflight bucket and into
  651. the `clean` bucket.
  652. @param {String} bucketType one of `created`, `updated`, or `deleted`
  653. */
  654. recordBecameClean: function(kind, record) {
  655. this.removeFromBucket(kind, record);
  656. this.remove(record);
  657. }
  658. });
  659. })();
  660. (function() {
  661. /*globals Ember*/
  662. var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
  663. var DATA_PROXY = {
  664. get: function(name) {
  665. return this.savedData[name];
  666. }
  667. };
  668. // These values are used in the data cache when clientIds are
  669. // needed but the underlying data has not yet been loaded by
  670. // the server.
  671. var UNLOADED = 'unloaded';
  672. var LOADING = 'loading';
  673. // Implementors Note:
  674. //
  675. // The variables in this file are consistently named according to the following
  676. // scheme:
  677. //
  678. // * +id+ means an identifier managed by an external source, provided inside the
  679. // data hash provided by that source.
  680. // * +clientId+ means a transient numerical identifier generated at runtime by
  681. // the data store. It is important primarily because newly created objects may
  682. // not yet have an externally generated id.
  683. // * +type+ means a subclass of DS.Model.
  684. /**
  685. The store contains all of the hashes for records loaded from the server.
  686. It is also responsible for creating instances of DS.Model when you request one
  687. of these data hashes, so that they can be bound to in your Handlebars templates.
  688. Create a new store like this:
  689. MyApp.store = DS.Store.create();
  690. You can retrieve DS.Model instances from the store in several ways. To retrieve
  691. a record for a specific id, use the `find()` method:
  692. var record = MyApp.store.find(MyApp.Contact, 123);
  693. By default, the store will talk to your backend using a standard REST mechanism.
  694. You can customize how the store talks to your backend by specifying a custom adapter:
  695. MyApp.store = DS.Store.create({
  696. adapter: 'MyApp.CustomAdapter'
  697. });
  698. You can learn more about writing a custom adapter by reading the `DS.Adapter`
  699. documentation.
  700. */
  701. DS.Store = Ember.Object.extend({
  702. /**
  703. Many methods can be invoked without specifying which store should be used.
  704. In those cases, the first store created will be used as the default. If
  705. an application has multiple stores, it should specify which store to use
  706. when performing actions, such as finding records by id.
  707. The init method registers this store as the default if none is specified.
  708. */
  709. init: function() {
  710. // Enforce API revisioning. See BREAKING_CHANGES.md for more.
  711. var revision = get(this, 'revision');
  712. if (revision !== DS.CURRENT_API_REVISION && !Ember.ENV.TESTING) {
  713. throw new Error("Error: The Ember Data library has had breaking API changes since the last time you updated the library. Please review the list of breaking changes at https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md, then update your store's `revision` property to " + DS.CURRENT_API_REVISION);
  714. }
  715. if (!get(DS, 'defaultStore') || get(this, 'isDefaultStore')) {
  716. set(DS, 'defaultStore', this);
  717. }
  718. // internal bookkeeping; not observable
  719. this.typeMaps = {};
  720. this.recordCache = [];
  721. this.clientIdToId = {};
  722. this.recordArraysByClientId = {};
  723. // Internally, we maintain a map of all unloaded IDs requested by
  724. // a ManyArray. As the adapter loads hashes into the store, the
  725. // store notifies any interested ManyArrays. When the ManyArray's
  726. // total number of loading records drops to zero, it becomes
  727. // `isLoaded` and fires a `didLoad` event.
  728. this.loadingRecordArrays = {};
  729. set(this, 'defaultTransaction', this.transaction());
  730. return this._super();
  731. },
  732. /**
  733. Returns a new transaction scoped to this store.
  734. @see {DS.Transaction}
  735. @returns DS.Transaction
  736. */
  737. transaction: function() {
  738. return DS.Transaction.create({ store: this });
  739. },
  740. /**
  741. @private
  742. This is used only by the record's DataProxy. Do not use this directly.
  743. */
  744. dataForRecord: function(record) {
  745. var type = record.constructor,
  746. clientId = get(record, 'clientId'),
  747. typeMap = this.typeMapFor(type);
  748. return typeMap.cidToHash[clientId];
  749. },
  750. /**
  751. The adapter to use to communicate to a backend server or other persistence layer.
  752. This can be specified as an instance, a class, or a property path that specifies
  753. where the adapter can be located.
  754. @property {DS.Adapter|String}
  755. */
  756. adapter: null,
  757. /**
  758. @private
  759. This property returns the adapter, after resolving a possible String.
  760. @returns DS.Adapter
  761. */
  762. _adapter: Ember.computed(function() {
  763. var adapter = get(this, 'adapter');
  764. if (typeof adapter === 'string') {
  765. return get(this, adapter, false) || get(window, adapter);
  766. }
  767. return adapter;
  768. }).property('adapter').cacheable(),
  769. // A monotonically increasing number to be used to uniquely identify
  770. // data hashes and records.
  771. clientIdCounter: 1,
  772. // .....................
  773. // . CREATE NEW RECORD .
  774. // .....................
  775. /**
  776. Create a new record in the current store. The properties passed
  777. to this method are set on the newly created record.
  778. @param {subclass of DS.Model} type
  779. @param {Object} properties a hash of properties to set on the
  780. newly created record.
  781. @returns DS.Model
  782. */
  783. createRecord: function(type, properties, transaction) {
  784. properties = properties || {};
  785. // Create a new instance of the model `type` and put it
  786. // into the specified `transaction`. If no transaction is
  787. // specified, the default transaction will be used.
  788. //
  789. // NOTE: A `transaction` is specified when the
  790. // `transaction.createRecord` API is used.
  791. var record = type._create({
  792. store: this
  793. });
  794. transaction = transaction || get(this, 'defaultTransaction');
  795. transaction.adoptRecord(record);
  796. // Extract the primary key from the `properties` hash,
  797. // based on the `primaryKey` for the model type.
  798. var primaryKey = get(record, 'primaryKey'),
  799. id = properties[primaryKey] || null;
  800. // If the passed properties do not include a primary key,
  801. // give the adapter an opportunity to generate one.
  802. var adapter;
  803. if (Ember.none(id)) {
  804. adapter = get(this, 'adapter');
  805. if (adapter && adapter.generateIdForRecord) {
  806. id = adapter.generateIdForRecord(this, record);
  807. properties.id = id;
  808. }
  809. }
  810. var hash = {}, clientId;
  811. // Push the hash into the store. If present, associate the
  812. // extracted `id` with the hash.
  813. clientId = this.pushHash(hash, id, type);
  814. record.send('didChangeData');
  815. var recordCache = get(this, 'recordCache');
  816. // Now that we have a clientId, attach it to the record we
  817. // just created.
  818. set(record, 'clientId', clientId);
  819. // Store the record we just created in the record cache for
  820. // this clientId.
  821. recordCache[clientId] = record;
  822. // Set the properties specified on the record.
  823. record.setProperties(properties);
  824. this.updateRecordArrays(type, clientId, get(record, 'data'));
  825. return record;
  826. },
  827. // .................
  828. // . DELETE RECORD .
  829. // .................
  830. /**
  831. For symmetry, a record can be deleted via the store.
  832. @param {DS.Model} record
  833. */
  834. deleteRecord: function(record) {
  835. record.send('deleteRecord');
  836. },
  837. // ................
  838. // . FIND RECORDS .
  839. // ................
  840. /**
  841. This is the main entry point into finding records. The first
  842. parameter to this method is always a subclass of `DS.Model`.
  843. You can use the `find` method on a subclass of `DS.Model`
  844. directly if your application only has one store. For
  845. example, instead of `store.find(App.Person, 1)`, you could
  846. say `App.Person.find(1)`.
  847. ---
  848. To find a record by ID, pass the `id` as the second parameter:
  849. store.find(App.Person, 1);
  850. App.Person.find(1);
  851. If the record with that `id` had not previously been loaded,
  852. the store will return an empty record immediately and ask
  853. the adapter to find the data by calling the adapter's `find`
  854. method.
  855. The `find` method will always return the same object for a
  856. given type and `id`. To check whether the adapter has populated
  857. a record, you can check its `isLoaded` property.
  858. ---
  859. To find all records for a type, call `find` with no additional
  860. parameters:
  861. store.find(App.Person);
  862. App.Person.find();
  863. This will return a `RecordArray` representing all known records
  864. for the given type and kick off a request to the adapter's
  865. `findAll` method to load any additional records for the type.
  866. The `RecordArray` returned by `find()` is live. If any more
  867. records for the type are added at a later time through any
  868. mechanism, it will automatically update to reflect the change.
  869. ---
  870. To find a record by a query, call `find` with a hash as the
  871. second parameter:
  872. store.find(App.Person, { page: 1 });
  873. App.Person.find({ page: 1 });
  874. This will return a `RecordArray` immediately, but it will always
  875. be an empty `RecordArray` at first. It will call the adapter's
  876. `findQuery` method, which will populate the `RecordArray` once
  877. the server has returned results.
  878. You can check whether a query results `RecordArray` has loaded
  879. by checking its `isLoaded` property.
  880. */
  881. find: function(type, id, query) {
  882. if (id === undefined) {
  883. return this.findAll(type);
  884. }
  885. if (query !== undefined) {
  886. return this.findMany(type, id, query);
  887. } else if (Ember.typeOf(id) === 'object') {
  888. return this.findQuery(type, id);
  889. }
  890. if (Ember.isArray(id)) {
  891. return this.findMany(type, id);
  892. }
  893. var clientId = this.typeMapFor(type).idToCid[id];
  894. return this.findByClientId(type, clientId, id);
  895. },
  896. findByClientId: function(type, clientId, id) {
  897. var recordCache = get(this, 'recordCache'),
  898. dataCache, record;
  899. // If there is already a clientId assigned for this
  900. // type/id combination, try to find an existing
  901. // record for that id and return. Otherwise,
  902. // materialize a new record and set its data to the
  903. // value we already have.
  904. if (clientId !== undefined) {
  905. record = recordCache[clientId];
  906. if (!record) {
  907. // create a new instance of the model type in the
  908. // 'isLoading' state
  909. record = this.materializeRecord(type, clientId);
  910. dataCache = this.typeMapFor(type).cidToHash;
  911. if (typeof dataCache[clientId] === 'object') {
  912. record.send('didChangeData');
  913. }
  914. }
  915. } else {
  916. clientId = this.pushHash(LOADING, id, type);
  917. // create a new instance of the model type in the
  918. // 'isLoading' state
  919. record = this.materializeRecord(type, clientId, id);
  920. // let the adapter set the data, possibly async
  921. var adapter = get(this, '_adapter');
  922. if (adapter && adapter.find) { adapter.find(this, type, id); }
  923. else { throw fmt("Adapter is either null or does not implement `find` method", this); }
  924. }
  925. return record;
  926. },
  927. /**
  928. @private
  929. Given a type and array of `clientId`s, determines which of those
  930. `clientId`s has not yet been loaded.
  931. In preparation for loading, this method also marks any unloaded
  932. `clientId`s as loading.
  933. */
  934. neededClientIds: function(type, clientIds) {
  935. var neededClientIds = [],
  936. typeMap = this.typeMapFor(type),
  937. dataCache = typeMap.cidToHash,
  938. clientId;
  939. for (var i=0, l=clientIds.length; i<l; i++) {
  940. clientId = clientIds[i];
  941. if (dataCache[clientId] === UNLOADED) {
  942. neededClientIds.push(clientId);
  943. dataCache[clientId] = LOADING;
  944. }
  945. }
  946. return neededClientIds;
  947. },
  948. /**
  949. @private
  950. This method is the entry point that associations use to update
  951. themselves when their underlying data changes.
  952. First, it determines which of its `clientId`s are still unloaded,
  953. then converts the needed `clientId`s to IDs and invokes `findMany`
  954. on the adapter.
  955. */
  956. fetchUnloadedClientIds: function(type, clientIds) {
  957. var neededClientIds = this.neededClientIds(type, clientIds);
  958. this.fetchMany(type, neededClientIds);
  959. },
  960. /**
  961. @private
  962. This method takes a type and list of `clientId`s, converts the
  963. `clientId`s into IDs, and then invokes the adapter's `findMany`
  964. method.
  965. It is used both by a brand new association (via the `findMany`
  966. method) or when the data underlying an existing association
  967. changes (via the `fetchUnloadedClientIds` method).
  968. */
  969. fetchMany: function(type, clientIds) {
  970. var clientIdToId = this.clientIdToId;
  971. var neededIds = Ember.EnumerableUtils.map(clientIds, function(clientId) {
  972. return clientIdToId[clientId];
  973. });
  974. if (!neededIds.length) { return; }
  975. var adapter = get(this, '_adapter');
  976. if (adapter && adapter.findMany) { adapter.findMany(this, type, neededIds); }
  977. else { throw fmt("Adapter is either null or does not implement `findMany` method", this); }
  978. },
  979. /**
  980. @private
  981. `findMany` is the entry point that associations use to generate a
  982. new `ManyArray` for the list of IDs specified by the server for
  983. the association.
  984. Its responsibilities are:
  985. * convert the IDs into clientIds
  986. * determine which of the clientIds still need to be loaded
  987. * create a new ManyArray whose content is *all* of the clientIds
  988. * notify the ManyArray of the number of its elements that are
  989. already loaded
  990. * insert the unloaded clientIds into the `loadingRecordArrays`
  991. bookkeeping structure, which will allow the `ManyArray` to know
  992. when all of its loading elements are loaded from the server.
  993. * ask the adapter to load the unloaded elements, by invoking
  994. findMany with the still-unloaded IDs.
  995. */
  996. findMany: function(type, ids) {
  997. // 1. Convert ids to client ids
  998. // 2. Determine which of the client ids need to be loaded
  999. // 3. Create a new ManyArray whose content is ALL of the clientIds
  1000. // 4. Decrement the ManyArray's counter by the number of loaded clientIds
  1001. // 5. Put the ManyArray into our bookkeeping data structure, keyed on
  1002. // the needed clientIds
  1003. // 6. Ask the adapter to load the records for the unloaded clientIds (but
  1004. // convert them back to ids)
  1005. var clientIds = this.clientIdsForIds(type, ids);
  1006. var neededClientIds = this.neededClientIds(type, clientIds),
  1007. manyArray = this.createManyArray(type, Ember.A(clientIds)),
  1008. loadedCount = clientIds.length - neededClientIds.length,
  1009. loadingRecordArrays = this.loadingRecordArrays,
  1010. clientId, i, l;
  1011. manyArray.send('loadedRecords', loadedCount);
  1012. if (neededClientIds.length) {
  1013. for (i=0, l=neededClientIds.length; i<l; i++) {
  1014. clientId = neededClientIds[i];
  1015. if (loadingRecordArrays[clientId]) {
  1016. loadingRecordArrays[clientId].push(manyArray);
  1017. } else {
  1018. this.loadingRecordArrays[clientId] = [ manyArray ];
  1019. }
  1020. }
  1021. this.fetchMany(type, neededClientIds);
  1022. }
  1023. return manyArray;
  1024. },
  1025. findQuery: function(type, query) {
  1026. var array = DS.AdapterPopulatedRecordArray.create({ type: type, content: Ember.A([]), store: this });
  1027. var adapter = get(this, '_adapter');
  1028. if (adapter && adapter.findQuery) { adapter.findQuery(this, type, query, array); }
  1029. else { throw fmt("Adapter is either null or does not implement `findQuery` method", this); }
  1030. return array;
  1031. },
  1032. findAll: function(type) {
  1033. var typeMap = this.typeMapFor(type),
  1034. findAllCache = typeMap.findAllCache;
  1035. if (findAllCache) { return findAllCache; }
  1036. var array = DS.RecordArray.create({ type: type, content: Ember.A([]), store: this });
  1037. this.registerRecordArray(array, type);
  1038. var adapter = get(this, '_adapter');
  1039. if (adapter && adapter.findAll) { adapter.findAll(this, type); }
  1040. typeMap.findAllCache = array;
  1041. return array;
  1042. },
  1043. filter: function(type, query, filter) {
  1044. // allow an optional server query
  1045. if (arguments.length === 3) {
  1046. this.findQuery(type, query);
  1047. } else if (arguments.length === 2) {
  1048. filter = query;
  1049. }
  1050. var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A([]), store: this, filterFunction: filter });
  1051. this.registerRecordArray(array, type, filter);
  1052. return array;
  1053. },
  1054. recordIsLoaded: function(type, id) {
  1055. return !Ember.none(this.typeMapFor(type).idToCid[id]);
  1056. },
  1057. // ............
  1058. // . UPDATING .
  1059. // ............
  1060. hashWasUpdated: function(type, clientId, record) {
  1061. // Because hash updates are invoked at the end of the run loop,
  1062. // it is possible that a record might be deleted after its hash
  1063. // has been modified and this method was scheduled to be called.
  1064. //
  1065. // If that's the case, the record would have already been removed
  1066. // from all record arrays; calling updateRecordArrays would just
  1067. // add it back. If the record is deleted, just bail. It shouldn't
  1068. // give us any more trouble after this.
  1069. if (get(record, 'isDeleted')) { return; }
  1070. this.updateRecordArrays(type, clientId, get(record, 'data'));
  1071. },
  1072. // ..............
  1073. // . PERSISTING .
  1074. // ..............
  1075. commit: function() {
  1076. var defaultTransaction = get(this, 'defaultTransaction');
  1077. set(this, 'defaultTransaction', this.transaction());
  1078. defaultTransaction.commit();
  1079. },
  1080. didUpdateRecords: function(array, hashes) {
  1081. if (hashes) {
  1082. array.forEach(function(record, idx) {
  1083. this.didUpdateRecord(record, hashes[idx]);
  1084. }, this);
  1085. } else {
  1086. array.forEach(function(record) {
  1087. this.didUpdateRecord(record);
  1088. }, this);
  1089. }
  1090. },
  1091. didUpdateRecord: function(record, hash) {
  1092. if (hash) {
  1093. var clientId = get(record, 'clientId'),
  1094. dataCache = this.typeMapFor(record.constructor).cidToHash;
  1095. dataCache[clientId] = hash;
  1096. record.send('didChangeData');
  1097. record.hashWasUpdated();
  1098. } else {
  1099. record.send('didSaveData');
  1100. }
  1101. record.send('didCommit');
  1102. },
  1103. didDeleteRecords: function(array) {
  1104. array.forEach(function(record) {
  1105. record.send('didCommit');
  1106. });
  1107. },
  1108. didDeleteRecord: function(record) {
  1109. record.send('didCommit');
  1110. },
  1111. _didCreateRecord: function(record, hash, typeMap, clientId, primaryKey) {
  1112. var recordData = get(record, 'data'), id, changes;
  1113. if (hash) {
  1114. typeMap.cidToHash[clientId] = hash;
  1115. // If the server returns a hash, we assume that the server's version
  1116. // of the data supercedes the local changes.
  1117. record.beginPropertyChanges();
  1118. record.send('didChangeData');
  1119. recordData.adapterDidUpdate();
  1120. record.hashWasUpdated();
  1121. record.endPropertyChanges();
  1122. id = hash[primaryKey];
  1123. typeMap.idToCid[id] = clientId;
  1124. this.clientIdToId[clientId] = id;
  1125. } else {
  1126. recordData.commit();
  1127. }
  1128. record.send('didCommit');
  1129. },
  1130. didCreateRecords: function(type, array, hashes) {
  1131. var primaryKey = type.proto().primaryKey,
  1132. typeMap = this.typeMapFor(type),
  1133. clientId;
  1134. for (var i=0, l=get(array, 'length'); i<l; i++) {
  1135. var record = array[i], hash = hashes[i];
  1136. clientId = get(record, 'clientId');
  1137. this._didCreateRecord(record, hash, typeMap, clientId, primaryKey);
  1138. }
  1139. },
  1140. didCreateRecord: function(record, hash) {
  1141. var type = record.constructor,
  1142. typeMap = this.typeMapFor(type),
  1143. clientId, primaryKey;
  1144. // The hash is optional, but if it is not provided, the client must have
  1145. // provided a primary key.
  1146. primaryKey = type.proto().primaryKey;
  1147. // TODO: Make Ember.assert more flexible
  1148. if (hash) {
  1149. Ember.assert("The server must provide a primary key: " + primaryKey, get(hash, primaryKey));
  1150. } else {
  1151. Ember.assert("The server did not return data, and you did not create a primary key (" + primaryKey + ") on the client", get(get(record, 'data'), primaryKey));
  1152. }
  1153. clientId = get(record, 'clientId');
  1154. this._didCreateRecord(record, hash, typeMap, clientId, primaryKey);
  1155. },
  1156. recordWasInvalid: function(record, errors) {
  1157. record.send('becameInvalid', errors);
  1158. },
  1159. // .................
  1160. // . RECORD ARRAYS .
  1161. // .................
  1162. registerRecordArray: function(array, type, filter) {
  1163. var recordArrays = this.typeMapFor(type).recordArrays;
  1164. recordArrays.push(array);
  1165. this.updateRecordArrayFilter(array, type, filter);
  1166. },
  1167. createManyArray: function(type, clientIds) {
  1168. var array = DS.ManyArray.create({ type: type, content: clientIds, store: this });
  1169. clientIds.forEach(function(clientId) {
  1170. var recordArrays = this.recordArraysForClientId(clientId);
  1171. recordArrays.add(array);
  1172. }, this);
  1173. return array;
  1174. },
  1175. updateRecordArrayFilter: function(array, type, filter) {
  1176. var typeMap = this.typeMapFor(type),
  1177. dataCache = typeMap.cidToHash,
  1178. clientIds = typeMap.clientIds,
  1179. clientId, hash, proxy;
  1180. var recordCache = get(this, 'recordCache'),
  1181. foundRecord,
  1182. record;
  1183. for (var i=0, l=clientIds.length; i<l; i++) {
  1184. clientId = clientIds[i];
  1185. foundRecord = false;
  1186. hash = dataCache[clientId];
  1187. if (typeof hash === 'object') {
  1188. if (record = recordCache[clientId]) {
  1189. if (!get(record, 'isDeleted')) {
  1190. proxy = get(record, 'data');
  1191. foundRecord = true;
  1192. }
  1193. } else {
  1194. DATA_PROXY.savedData = hash;
  1195. proxy = DATA_PROXY;
  1196. foundRecord = true;
  1197. }
  1198. if (foundRecord) { this.updateRecordArray(array, filter, type, clientId, proxy); }
  1199. }
  1200. }
  1201. },
  1202. updateRecordArrays: function(type, clientId, dataProxy) {
  1203. var recordArrays = this.typeMapFor(type).recordArrays,
  1204. filter;
  1205. recordArrays.forEach(function(array) {
  1206. filter = get(array, 'filterFunction');
  1207. this.updateRecordArray(array, filter, type, clientId, dataProxy);
  1208. }, this);
  1209. // loop through all manyArrays containing an unloaded copy of this
  1210. // clientId and notify them that the record was loaded.
  1211. var manyArrays = this.loadingRecordArrays[clientId], manyArray;
  1212. if (manyArrays) {
  1213. for (var i=0, l=manyArrays.length; i<l; i++) {
  1214. manyArrays[i].send('loadedRecords', 1);
  1215. }
  1216. this.loadingRecordArrays[clientId] = null;
  1217. }
  1218. },
  1219. updateRecordArray: function(array, filter, type, clientId, dataProxy) {
  1220. var shouldBeInArray;
  1221. if (!filter) {
  1222. shouldBeInArray = true;
  1223. } else {
  1224. shouldBeInArray = filter(dataProxy);
  1225. }
  1226. var content = get(array, 'content');
  1227. var alreadyInArray = content.indexOf(clientId) !== -1;
  1228. var recordArrays = this.recordArraysForClientId(clientId);
  1229. if (shouldBeInArray && !alreadyInArray) {
  1230. recordArrays.add(array);
  1231. content.pushObject(clientId);
  1232. } else if (!shouldBeInArray && alreadyInArray) {
  1233. recordArrays.remove(array);
  1234. content.removeObject(clientId);
  1235. }
  1236. },
  1237. removeFromRecordArrays: function(record) {
  1238. var clientId = get(record, 'clientId');
  1239. var recordArrays = this.recordArraysForClientId(clientId);
  1240. recordArrays.forEach(function(array) {
  1241. var content = get(array, 'content');
  1242. content.removeObject(clientId);
  1243. });
  1244. },
  1245. // ............
  1246. // . INDEXING .
  1247. // ............
  1248. recordArraysForClientId: function(clientId) {
  1249. var recordArrays = get(this, 'recordArraysByClientId');
  1250. var ret = recordArrays[clientId];
  1251. if (!ret) {
  1252. ret = recordArrays[clientId] = Ember.OrderedSet.create();
  1253. }
  1254. return ret;
  1255. },
  1256. typeMapFor: function(type) {
  1257. var typeMaps = get(this, 'typeMaps');
  1258. var guidForType = Ember.guidFor(type);
  1259. var typeMap = typeMaps[guidForType];
  1260. if (typeMap) {
  1261. return typeMap;
  1262. } else {
  1263. return (typeMaps[guidForType] =
  1264. {
  1265. idToCid: {},
  1266. clientIds: [],
  1267. cidToHash: {},
  1268. recordArrays: []
  1269. });
  1270. }
  1271. },
  1272. /** @private
  1273. For a given type and id combination, returns the client id used by the store.
  1274. If no client id has been assigned yet, one will be created and returned.
  1275. @param {DS.Model} type
  1276. @param {String|Number} id
  1277. */
  1278. clientIdForId: function(type, id) {
  1279. var clientId = this.typeMapFor(type).idToCid[id];
  1280. if (clientId !== undefined) { return clientId; }
  1281. return this.pushHash(UNLOADED, id, type);
  1282. },
  1283. /**
  1284. @private
  1285. This method works exactly like `clientIdForId`, but does not
  1286. require looking up the `typeMap` for every `clientId` and
  1287. invoking a method per `clientId`.
  1288. */
  1289. clientIdsForIds: function(type, ids) {
  1290. var typeMap = this.typeMapFor(type),
  1291. idToClientIdMap = typeMap.idToCid;
  1292. return Ember.EnumerableUtils.map(ids, function(id) {
  1293. var clientId = idToClientIdMap[id];
  1294. if (clientId) { return clientId; }
  1295. return this.pushHash(UNLOADED, id, type);
  1296. }, this);
  1297. },
  1298. // ................
  1299. // . LOADING DATA .
  1300. // ................
  1301. /**
  1302. Load a new data hash into the store for a given id and type combination.
  1303. If data for that record had been loaded previously, the new information
  1304. overwrites the old.
  1305. If the record you are loading data for has outstanding changes that have not
  1306. yet been saved, an exception will be thrown.
  1307. @param {DS.Model} type
  1308. @param {String|Number} id
  1309. @param {Object} hash the data hash to load
  1310. */
  1311. load: function(type, id, hash) {
  1312. if (hash === undefined) {
  1313. hash = id;
  1314. var primaryKey = type.proto().primaryKey;
  1315. Ember.assert("A data hash was loaded for a record of type " + type.toString() + " but no primary key '" + primaryKey + "' was provided.", primaryKey in hash);
  1316. id = hash[primaryKey];
  1317. }
  1318. var typeMap = this.typeMapFor(type),
  1319. dataCache = typeMap.cidToHash,
  1320. clientId = typeMap.idToCid[id],
  1321. recordCache = get(this, 'recordCache');
  1322. if (clientId !== undefined) {
  1323. dataCache[clientId] = hash;
  1324. var record = recordCache[clientId];
  1325. if (record) {
  1326. record.send('didChangeData');
  1327. }
  1328. } else {
  1329. clientId = this.pushHash(hash, id, type);
  1330. }
  1331. DATA_PROXY.savedData = hash;
  1332. this.updateRecordArrays(type, clientId, DATA_PROXY);
  1333. return { id: id, clientId: clientId };
  1334. },
  1335. loadMany: function(type, ids, hashes) {
  1336. var clientIds = Ember.A([]);
  1337. if (hashes === undefined) {
  1338. hashes = ids;
  1339. ids = [];
  1340. var primaryKey = type.proto().primaryKey;
  1341. ids = Ember.EnumerableUtils.map(hashes, function(hash) {
  1342. return hash[primaryKey];
  1343. });
  1344. }
  1345. for (var i=0, l=get(ids, 'length'); i<l; i++) {
  1346. var loaded = this.load(type, ids[i], hashes[i]);
  1347. clientIds.pushObject(loaded.clientId);
  1348. }
  1349. return { clientIds: clientIds, ids: ids };
  1350. },
  1351. /** @private
  1352. Stores a data hash for the specified type and id combination and returns
  1353. the client id.
  1354. @param {Object} hash
  1355. @param {String|Number} id
  1356. @param {DS.Model} type
  1357. @returns {Number}
  1358. */
  1359. pushHash: function(hash, id, type) {
  1360. var typeMap = this.typeMapFor(type);
  1361. var idToClientIdMap = typeMap.idToCid,
  1362. clientIdToIdMap = this.clientIdToId,
  1363. clientIds = typeMap.clientIds,
  1364. dataCache = typeMap.cidToHash;
  1365. var clientId = ++this.clientIdCounter;
  1366. dataCache[clientId] = hash;
  1367. // if we're creating an item, this process will be done
  1368. // later, once the object has been persisted.
  1369. if (id) {
  1370. idToClientIdMap[id] = clientId;
  1371. clientIdToIdMap[clientId] = id;
  1372. }
  1373. clientIds.push(clientId);
  1374. return clientId;
  1375. },
  1376. // ..........................
  1377. // . RECORD MATERIALIZATION .
  1378. // ..........................
  1379. materializeRecord: function(type, clientId, id) {
  1380. var record;
  1381. get(this, 'recordCache')[clientId] = record = type._create({
  1382. store: this,
  1383. clientId: clientId,
  1384. _id: id
  1385. });
  1386. get(this, 'defaultTransaction').adoptRecord(record);
  1387. record.send('loadingData');
  1388. return record;
  1389. },
  1390. destroy: function() {
  1391. if (get(DS, 'defaultStore') === this) {
  1392. set(DS, 'defaultStore', null);
  1393. }
  1394. return this._super();
  1395. }
  1396. });
  1397. })();
  1398. (function() {
  1399. var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor;
  1400. /**
  1401. This file encapsulates the various states that a record can transition
  1402. through during its lifecycle.
  1403. ### State Manager
  1404. A record's state manager explicitly tracks what state a record is in
  1405. at any given time. For instance, if a record is newly created and has
  1406. not yet been sent to the adapter to be saved, it would be in the
  1407. `created.uncommitted` state. If a record has had local modifications
  1408. made to it that are in the process of being saved, the record would be
  1409. in the `updated.inFlight` state. (These state paths will be explained
  1410. in more detail below.)
  1411. Events are sent by the record or its store to the record's state manager.
  1412. How the state manager reacts to these events is dependent on which state
  1413. it is in. In some states, certain events will be invalid and will cause
  1414. an exception to be raised.
  1415. States are hierarchical. For example, a record can be in the
  1416. `deleted.start` state, then transition into the `deleted.inFlight` state.
  1417. If a child state does not implement an event handler, the state manager
  1418. will attempt to invoke the event on all parent states until the root state is
  1419. reached. The state hierarchy of a record is described in terms of a path
  1420. string. You can determine a record's current state by getting its manager's
  1421. current state path:
  1422. record.get('stateManager.currentState.path');
  1423. //=> "created.uncommitted"
  1424. The `DS.Model` states are themselves stateless. What we mean is that,
  1425. though each instance of a record also has a unique instance of a
  1426. `DS.StateManager`, the hierarchical states that each of *those* points
  1427. to is a shared data structure. For performance reasons, instead of each
  1428. record getting its own copy of the hierarchy of states, each state
  1429. manager points to this global, immutable shared instance. How does a
  1430. state know which record it should be acting on? We pass a reference to
  1431. the current state manager as the first parameter to every method invoked
  1432. on a state.
  1433. The state manager passed as the first parameter is where you should stash
  1434. state about the record if needed; you should never store data on the state
  1435. object itself. If you need access to the record being acted on, you can
  1436. retrieve the state manager's `record` property. For example, if you had
  1437. an event handler `myEvent`:
  1438. myEvent: function(manager) {
  1439. var record = manager.get('record');
  1440. record.doSomething();
  1441. }
  1442. For more information about state managers in general, see the Ember.js
  1443. documentation on `Ember.StateManager`.
  1444. ### Events, Flags, and Transitions
  1445. A state may implement zero or more events, flags, or transitions.
  1446. #### Events
  1447. Events are named functions that are invoked when sent to a record. The
  1448. state manager will first look for a method with the given name on the
  1449. current state. If no method is found, it will search the current state's
  1450. parent, and then its grandparent, and so on until reaching the top of
  1451. the hierarchy. If the root is reached without an event handler being found,
  1452. an exception will be raised. This can be very helpful when debugging new
  1453. features.
  1454. Here's an example implementation of a state with a `myEvent` event handler:
  1455. aState: DS.State.create({
  1456. myEvent: function(manager, param) {
  1457. console.log("Received myEvent with "+param);
  1458. }
  1459. })
  1460. To trigger this event:
  1461. record.send('myEvent', 'foo');
  1462. //=> "Received myEvent with foo"
  1463. Note that an optional parameter can be sent to a record's `send()` method,
  1464. which will be passed as the second parameter to the event handler.
  1465. Events should transition to a different state if appropriate. This can be
  1466. done by calling the state manager's `goToState()` method with a path to the
  1467. desired state. The state manager will attempt to resolve the state path
  1468. relative to the current state. If no state is found at that path, it will
  1469. attempt to resolve it relative to the current state's parent, and then its
  1470. parent, and so on until the root is reached. For example, imagine a hierarchy
  1471. like this:
  1472. * created
  1473. * start <-- currentState
  1474. * inFlight
  1475. * updated
  1476. * inFlight
  1477. If we are currently in the `start` state, calling
  1478. `goToState('inFlight')` would transition to the `created.inFlight` state,
  1479. while calling `goToState('updated.inFlight')` would transition to
  1480. the `updated.inFlight` state.
  1481. Remember that *only events* should ever cause a state transition. You should
  1482. never call `goToState()` from outside a state's event handler. If you are
  1483. tempted to do so, create a new event and send that to the state manager.
  1484. #### Flags
  1485. Flags are Boolean values that can be used to introspect a record's current
  1486. state in a more user-friendly way than examining its state path. For example,
  1487. instead of doing this:
  1488. var statePath = record.get('stateManager.currentState.path');
  1489. if (statePath === 'created.inFlight') {
  1490. doSomething();
  1491. }
  1492. You can say:
  1493. if (record.get('isNew') && record.get('isSaving')) {
  1494. doSomething();
  1495. }
  1496. If your state does not set a value for a given flag, the value will
  1497. be inherited from its parent (or the first place in the state hierarchy
  1498. where it is defined).
  1499. The current set of flags are defined below. If you want to add a new flag,
  1500. in addition to the area below, you will also need to declare it in the
  1501. `DS.Model` class.
  1502. #### Transitions
  1503. Transitions are like event handlers but are called automatically upon
  1504. entering or exiting a state. To implement a transition, just call a method
  1505. either `enter` or `exit`:
  1506. myState: DS.State.create({
  1507. // Gets called automatically when entering
  1508. // this state.
  1509. enter: function(manager) {
  1510. console.log("Entered myState");
  1511. }
  1512. })
  1513. Note that enter and exit events are called once per transition. If the
  1514. current state changes, but changes to another child state of the parent,
  1515. the transition event on the parent will not be triggered.
  1516. */
  1517. var stateProperty = Ember.computed(function(key) {
  1518. var parent = get(this, 'parentState');
  1519. if (parent) {
  1520. return get(parent, key);
  1521. }
  1522. }).property();
  1523. var isEmptyObject = function(object) {
  1524. for (var name in object) {
  1525. if (object.hasOwnProperty(name)) { return false; }
  1526. }
  1527. return true;
  1528. };
  1529. var hasDefinedProperties = function(object) {
  1530. for (var name in object) {
  1531. if (object.hasOwnProperty(name) && object[name]) { return true; }
  1532. }
  1533. return false;
  1534. };
  1535. DS.State = Ember.State.extend({
  1536. isLoaded: stateProperty,
  1537. isDirty: stateProperty,
  1538. isSaving: stateProperty,
  1539. isDeleted: stateProperty,
  1540. isError: stateProperty,
  1541. isNew: stateProperty,
  1542. isValid: stateProperty,
  1543. isPending: stateProperty,
  1544. // For states that are substates of a
  1545. // DirtyState (updated or created), it is
  1546. // useful to be able to determine which
  1547. // type of dirty state it is.
  1548. dirtyType: stateProperty
  1549. });
  1550. var setProperty = function(manager, context) {
  1551. var key = context.key, value = context.value;
  1552. var record = get(manager, 'record'),
  1553. data = get(record, 'data');
  1554. set(data, key, value);
  1555. };
  1556. var setAssociation = function(manager, context) {
  1557. var key = context.key, value = context.value;
  1558. var record = get(manager, 'record'),
  1559. data = get(record, 'data');
  1560. data.setAssociation(key, value);
  1561. };
  1562. var didChangeData = function(manager) {
  1563. var record = get(manager, 'record'),
  1564. data = get(record, 'data');
  1565. data._savedData = null;
  1566. record.notifyPropertyChange('data');
  1567. };
  1568. // The waitingOn event shares common functionality
  1569. // between the different dirty states, but each is
  1570. // treated slightly differently. This method is exposed
  1571. // so that each implementation can invoke the common
  1572. // behavior, and then implement the behavior specific
  1573. // to the state.
  1574. var waitingOn = function(manager, object) {
  1575. var record = get(manager, 'record'),
  1576. pendingQueue = get(record, 'pendingQueue'),
  1577. objectGuid = guidFor(object);
  1578. var observer = function() {
  1579. if (get(object, 'id')) {
  1580. manager.send('doneWaitingOn', object);
  1581. Ember.removeObserver(object, 'id', observer);
  1582. }
  1583. };
  1584. pendingQueue[objectGuid] = [object, observer];
  1585. Ember.addObserver(object, 'id', observer);
  1586. };
  1587. // Implementation notes:
  1588. //
  1589. // Each state has a boolean value for all of the following flags:
  1590. //
  1591. // * isLoaded: The record has a populated `data` property. When a
  1592. // record is loaded via `store.find`, `isLoaded` is false
  1593. // until the adapter sets it. When a record is created locally,
  1594. // its `isLoaded` property is always true.
  1595. // * isDirty: The record has local changes that have not yet been
  1596. // saved by the adapter. This includes records that have been
  1597. // created (but not yet saved) or deleted.
  1598. // * isSaving: The record's transaction has been committed, but
  1599. // the adapter has not yet acknowledged that the changes have
  1600. // been persisted to the backend.
  1601. // * isDeleted: The record was marked for deletion. When `isDeleted`
  1602. // is true and `isDirty` is true, the record is deleted locally
  1603. // but the deletion was not yet persisted. When `isSaving` is
  1604. // true, the change is in-flight. When both `isDirty` and
  1605. // `isSaving` are false, the change has persisted.
  1606. // * isError: The adapter reported that it was unable to save
  1607. // local changes to the backend. This may also result in the
  1608. // record having its `isValid` property become false if the
  1609. // adapter reported that server-side validations failed.
  1610. // * isNew: The record was created on the client and the adapter
  1611. // did not yet report that it was successfully saved.
  1612. // * isValid: No client-side validations have failed and the
  1613. // adapter did not report any server-side validation failures.
  1614. // * isPending: A record `isPending` when it belongs to an
  1615. // association on another record and that record has not been
  1616. // saved. A record in this state cannot be saved because it
  1617. // lacks a "foreign key" that will be supplied by its parent
  1618. // association when the parent record has been created. When
  1619. // the adapter reports that the parent has saved, the
  1620. // `isPending` property on all children will become `false`
  1621. // and the transaction will try to commit the records.
  1622. // This mixin is mixed into various uncommitted states. Make
  1623. // sure to mix it in *after* the class definition, so its
  1624. // super points to the class definition.
  1625. var Uncommitted = Ember.Mixin.create({
  1626. setProperty: setProperty,
  1627. setAssociation: setAssociation
  1628. });
  1629. // These mixins are mixed into substates of the concrete
  1630. // subclasses of DirtyState.
  1631. var CreatedUncommitted = Ember.Mixin.create({
  1632. deleteRecord: function(manager) {
  1633. var record = get(manager, 'record');
  1634. this._super(manager);
  1635. record.withTransaction(function(t) {
  1636. t.recordBecameClean('created', record);
  1637. });
  1638. manager.goToState('deleted.saved');
  1639. }
  1640. });
  1641. var UpdatedUncommitted = Ember.Mixin.create({
  1642. deleteRecord: function(manager) {
  1643. this._super(manager);
  1644. var record = get(manager, 'record');
  1645. record.withTransaction(function(t) {
  1646. t.recordBecameClean('updated', record);
  1647. });
  1648. manager.goToState('deleted');
  1649. }
  1650. });
  1651. // The dirty state is a abstract state whose functionality is
  1652. // shared between the `created` and `updated` states.
  1653. //
  1654. // The deleted state shares the `isDirty` flag with the
  1655. // subclasses of `DirtyState`, but with a very different
  1656. // implementation.
  1657. var DirtyState = DS.State.extend({
  1658. initialState: 'uncommitted',
  1659. // FLAGS
  1660. isDirty: true,
  1661. // SUBSTATES
  1662. // When a record first becomes dirty, it is `uncommitted`.
  1663. // This means that there are local pending changes,
  1664. // but they have not yet begun to be saved.
  1665. uncommitted: DS.State.extend({
  1666. // TRANSITIONS
  1667. enter: function(manager) {
  1668. var dirtyType = get(this, 'dirtyType'),
  1669. record = get(manager, 'record');
  1670. record.withTransaction(function (t) {
  1671. t.recordBecameDirty(dirtyType, record);
  1672. });
  1673. },
  1674. // EVENTS
  1675. deleteRecord: Ember.K,
  1676. waitingOn: function(manager, object) {
  1677. waitingOn(manager, object);
  1678. manager.goToState('pending');
  1679. },
  1680. willCommit: function(manager) {
  1681. manager.goToState('inFlight');
  1682. },
  1683. becameInvalid: function(manager) {
  1684. var dirtyType = get(this, 'dirtyType'),
  1685. record = get(manager, 'record');
  1686. record.withTransaction(function (t) {
  1687. t.recordBecameInFlight(dirtyType, record);
  1688. });
  1689. manager.goToState('invalid');
  1690. },
  1691. rollback: function(manager) {
  1692. var record = get(manager, 'record'),
  1693. dirtyType = get(this, 'dirtyType'),
  1694. data = get(record, 'data');
  1695. data.rollback();
  1696. record.withTransaction(function(t) {
  1697. t.recordBecameClean(dirtyType, record);
  1698. });
  1699. manager.goToState('saved');
  1700. }
  1701. }, Uncommitted),
  1702. // Once a record has been handed off to the adapter to be
  1703. // saved, it is in the 'in flight' state. Changes to the
  1704. // record cannot be made during this window.
  1705. inFlight: DS.State.extend({
  1706. // FLAGS
  1707. isSaving: true,
  1708. // TRANSITIONS
  1709. enter: function(manager) {
  1710. var dirtyType = get(this, 'dirtyType'),
  1711. record = get(manager, 'record');
  1712. record.withTransaction(function (t) {
  1713. t.recordBecameInFlight(dirtyType, record);
  1714. });
  1715. },
  1716. // EVENTS
  1717. didCommit: function(manager) {
  1718. var dirtyType = get(this, 'dirtyType'),
  1719. record = get(manager, 'record');
  1720. record.withTransaction(function(t) {
  1721. t.recordBecameClean('inflight', record);
  1722. });
  1723. manager.goToState('saved');
  1724. manager.send('invokeLifecycleCallbacks', dirtyType);
  1725. },
  1726. becameInvalid: function(manager, errors) {
  1727. var record = get(manager, 'record');
  1728. set(record, 'errors', errors);
  1729. manager.goToState('invalid');
  1730. manager.send('invokeLifecycleCallbacks');
  1731. },
  1732. becameError: function(manager) {
  1733. manager.goToState('error');
  1734. manager.send('invokeLifecycleCallbacks');
  1735. },
  1736. didChangeData: didChangeData
  1737. }),
  1738. // If a record becomes associated with a newly created
  1739. // parent record, it will be `pending` until the parent
  1740. // record has successfully persisted. Once this happens,
  1741. // this record can use the parent's primary key as its
  1742. // foreign key.
  1743. //
  1744. // If the record's transaction had already started to
  1745. // commit, the record will transition to the `inFlight`
  1746. // state. If it had not, the record will transition to
  1747. // the `uncommitted` state.
  1748. pending: DS.State.extend({
  1749. initialState: 'uncommitted',
  1750. // FLAGS
  1751. isPending: true,
  1752. // SUBSTATES
  1753. // A pending record whose transaction has not yet
  1754. // started to commit is in this state.
  1755. uncommitted: DS.State.extend({
  1756. // EVENTS
  1757. deleteRecord: function(manager) {
  1758. var record = get(manager, 'record'),
  1759. pendingQueue = get(record, 'pendingQueue'),
  1760. tuple;
  1761. // since we are leaving the pending state, remove any
  1762. // observers we have registered on other records.
  1763. for (var prop in pendingQueue) {
  1764. if (!pendingQueue.hasOwnProperty(prop)) { continue; }
  1765. tuple = pendingQueue[prop];
  1766. Ember.removeObserver(tuple[0], 'id', tuple[1]);
  1767. }
  1768. },
  1769. willCommit: function(manager) {
  1770. manager.goToState('committing');
  1771. },
  1772. doneWaitingOn: function(manager, object) {
  1773. var record = get(manager, 'record'),
  1774. pendingQueue = get(record, 'pendingQueue'),
  1775. objectGuid = guidFor(object);
  1776. delete pendingQueue[objectGuid];
  1777. if (isEmptyObject(pendingQueue)) {
  1778. manager.send('doneWaiting');
  1779. }
  1780. },
  1781. doneWaiting: function(manager) {
  1782. var dirtyType = get(this, 'dirtyType');
  1783. manager.goToState(dirtyType + '.uncommitted');
  1784. }
  1785. }, Uncommitted),
  1786. // A pending record whose transaction has started
  1787. // to commit is in this state. Since it has not yet
  1788. // been sent to the adapter, it is not `inFlight`
  1789. // until all of its dependencies have been committed.
  1790. committing: DS.State.extend({
  1791. // FLAGS
  1792. isSaving: true,
  1793. // EVENTS
  1794. doneWaitingOn: function(manager, object) {
  1795. var record = get(manager, 'record'),
  1796. pendingQueue = get(record, 'pendingQueue'),
  1797. objectGuid = guidFor(object);
  1798. delete pendingQueue[objectGuid];
  1799. if (isEmptyObject(pendingQueue)) {
  1800. manager.send('doneWaiting');
  1801. }
  1802. },
  1803. doneWaiting: function(manager) {
  1804. var record = get(manager, 'record'),
  1805. transaction = get(record, 'transaction');
  1806. // Now that the record is no longer pending, schedule
  1807. // the transaction to commit.
  1808. Ember.run.once(transaction, transaction.commit);
  1809. },
  1810. willCommit: function(manager) {
  1811. var record = get(manager, 'record'),
  1812. pendingQueue = get(record, 'pendingQueue');
  1813. if (isEmptyObject(pendingQueue)) {
  1814. var dirtyType = get(this, 'dirtyType');
  1815. manager.goToState(dirtyType + '.inFlight');
  1816. }
  1817. }
  1818. })
  1819. }),
  1820. // A record is in the `invalid` state when its client-side
  1821. // invalidations have failed, or if the adapter has indicated
  1822. // the the record failed server-side invalidations.
  1823. invalid: DS.State.extend({
  1824. // FLAGS
  1825. isValid: false,
  1826. exit: function(manager) {
  1827. var record = get(manager, 'record');
  1828. record.withTransaction(function (t) {
  1829. t.recordBecameClean('inflight', record);
  1830. });
  1831. },
  1832. // EVENTS
  1833. deleteRecord: function(manager) {
  1834. manager.goToState('deleted');
  1835. },
  1836. setAssociation: setAssociation,
  1837. setProperty: function(manager, context) {
  1838. setProperty(manager, context);
  1839. var record = get(manager, 'record'),
  1840. errors = get(record, 'errors'),
  1841. key = context.key;
  1842. set(errors, key, null);
  1843. if (!hasDefinedProperties(errors)) {
  1844. manager.send('becameValid');
  1845. }
  1846. },
  1847. rollback: function(manager) {
  1848. manager.send('becameValid');
  1849. manager.send('rollback');
  1850. },
  1851. becameValid: function(manager) {
  1852. manager.goToState('uncommitted');
  1853. },
  1854. invokeLifecycleCallbacks: function(manager) {
  1855. var record = get(manager, 'record');
  1856. record.trigger('becameInvalid', record);
  1857. }
  1858. })
  1859. });
  1860. // The created and updated states are created outside the state
  1861. // chart so we can reopen their substates and add mixins as
  1862. // necessary.
  1863. var createdState = DirtyState.create({
  1864. dirtyType: 'created',
  1865. // FLAGS
  1866. isNew: true
  1867. });
  1868. var updatedState = DirtyState.create({
  1869. dirtyType: 'updated'
  1870. });
  1871. // The created.uncommitted state and created.pending.uncommitted share
  1872. // some logic defined in CreatedUncommitted.
  1873. createdState.states.uncommitted.reopen(CreatedUncommitted);
  1874. createdState.states.pending.states.uncommitted.reopen(CreatedUncommitted);
  1875. // The created.uncommitted state needs to immediately transition to the
  1876. // deleted state if it is rolled back.
  1877. createdState.states.uncommitted.reopen({
  1878. rollback: function(manager) {
  1879. this._super(manager);
  1880. manager.goToState('deleted.saved');
  1881. }
  1882. });
  1883. // The updated.uncommitted state and updated.pending.uncommitted share
  1884. // some logic defined in UpdatedUncommitted.
  1885. updatedState.states.uncommitted.reopen(UpdatedUncommitted);
  1886. updatedState.states.pending.states.uncommitted.reopen(UpdatedUncommitted);
  1887. updatedState.states.inFlight.reopen({
  1888. didSaveData: function(manager) {
  1889. var record = get(manager, 'record'),
  1890. data = get(record, 'data');
  1891. data.saveData();
  1892. data.adapterDidUpdate();
  1893. }
  1894. });
  1895. var states = {
  1896. rootState: Ember.State.create({
  1897. // FLAGS
  1898. isLoaded: false,
  1899. isDirty: false,
  1900. isSaving: false,
  1901. isDeleted: false,
  1902. isError: false,
  1903. isNew: false,
  1904. isValid: true,
  1905. isPending: false,
  1906. // SUBSTATES
  1907. // A record begins its lifecycle in the `empty` state.
  1908. // If its data will come from the adapter, it will
  1909. // transition into the `loading` state. Otherwise, if
  1910. // the record is being created on the client, it will
  1911. // transition into the `created` state.
  1912. empty: DS.State.create({
  1913. // EVENTS
  1914. loadingData: function(manager) {
  1915. manager.goToState('loading');
  1916. },
  1917. didChangeData: function(manager) {
  1918. didChangeData(manager);
  1919. manager.goToState('loaded.created');
  1920. }
  1921. }),
  1922. // A record enters this state when the store askes
  1923. // the adapter for its data. It remains in this state
  1924. // until the adapter provides the requested data.
  1925. //
  1926. // Usually, this process is asynchronous, using an
  1927. // XHR to retrieve the data.
  1928. loading: DS.State.create({
  1929. // TRANSITIONS
  1930. exit: function(manager) {
  1931. var record = get(manager, 'record');
  1932. record.trigger('didLoad');
  1933. },
  1934. // EVENTS
  1935. didChangeData: function(manager, data) {
  1936. didChangeData(manager);
  1937. manager.send('loadedData');
  1938. },
  1939. loadedData: function(manager) {
  1940. manager.goToState('loaded');
  1941. }
  1942. }),
  1943. // A record enters this state when its data is populated.
  1944. // Most of a record's lifecycle is spent inside substates
  1945. // of the `loaded` state.
  1946. loaded: DS.State.create({
  1947. initialState: 'saved',
  1948. // FLAGS
  1949. isLoaded: true,
  1950. // SUBSTATES
  1951. // If there are no local changes to a record, it remains
  1952. // in the `saved` state.
  1953. saved: DS.State.create({
  1954. // EVENTS
  1955. setProperty: function(manager, context) {
  1956. setProperty(manager, context);
  1957. manager.goToState('updated');
  1958. },
  1959. setAssociation: function(manager, context) {
  1960. setAssociation(manager, context);
  1961. manager.goToState('updated');
  1962. },
  1963. didChangeData: didChangeData,
  1964. deleteRecord: function(manager) {
  1965. manager.goToState('deleted');
  1966. },
  1967. waitingOn: function(manager, object) {
  1968. waitingOn(manager, object);
  1969. manager.goToState('updated.pending');
  1970. },
  1971. invokeLifecycleCallbacks: function(manager, dirtyType) {
  1972. var record = get(manager, 'record');
  1973. if (dirtyType === 'created') {
  1974. record.trigger('didCreate', record);
  1975. } else {
  1976. record.trigger('didUpdate', record);
  1977. }
  1978. }
  1979. }),
  1980. // A record is in this state after it has been locally
  1981. // created but before the adapter has indicated that
  1982. // it has been saved.
  1983. created: createdState,
  1984. // A record is in this state if it has already been
  1985. // saved to the server, but there are new local changes
  1986. // that have not yet been saved.
  1987. updated: updatedState
  1988. }),
  1989. // A record is in this state if it was deleted from the store.
  1990. deleted: DS.State.create({
  1991. // FLAGS
  1992. isDeleted: true,
  1993. isLoaded: true,
  1994. isDirty: true,
  1995. // TRANSITIONS
  1996. enter: function(manager) {
  1997. var record = get(manager, 'record'),
  1998. store = get(record, 'store');
  1999. store.removeFromRecordArrays(record);
  2000. },
  2001. // SUBSTATES
  2002. // When a record is deleted, it enters the `start`
  2003. // state. It will exit this state when the record's
  2004. // transaction starts to commit.
  2005. start: DS.State.create({
  2006. // TRANSITIONS
  2007. enter: function(manager) {
  2008. var record = get(manager, 'record');
  2009. record.withTransaction(function(t) {
  2010. t.recordBecameDirty('deleted', record);
  2011. });
  2012. },
  2013. // EVENTS
  2014. willCommit: function(manager) {
  2015. manager.goToState('inFlight');
  2016. },
  2017. rollback: function(manager) {
  2018. var record = get(manager, 'record'),
  2019. data = get(record, 'data');
  2020. data.rollback();
  2021. record.withTransaction(function(t) {
  2022. t.recordBecameClean('deleted', record);
  2023. });
  2024. manager.goToState('loaded');
  2025. }
  2026. }),
  2027. // After a record's transaction is committing, but
  2028. // before the adapter indicates that the deletion
  2029. // has saved to the server, a record is in the
  2030. // `inFlight` substate of `deleted`.
  2031. inFlight: DS.State.create({
  2032. // FLAGS
  2033. isSaving: true,
  2034. // TRANSITIONS
  2035. enter: function(manager) {
  2036. var record = get(manager, 'record');
  2037. record.withTransaction(function (t) {
  2038. t.recordBecameInFlight('deleted', record);
  2039. });
  2040. },
  2041. // EVENTS
  2042. didCommit: function(manager) {
  2043. var record = get(manager, 'record');
  2044. record.withTransaction(function(t) {
  2045. t.recordBecameClean('inflight', record);
  2046. });
  2047. manager.goToState('saved');
  2048. manager.send('invokeLifecycleCallbacks');
  2049. }
  2050. }),
  2051. // Once the adapter indicates that the deletion has
  2052. // been saved, the record enters the `saved` substate
  2053. // of `deleted`.
  2054. saved: DS.State.create({
  2055. // FLAGS
  2056. isDirty: false,
  2057. invokeLifecycleCallbacks: function(manager) {
  2058. var record = get(manager, 'record');
  2059. record.trigger('didDelete', record);
  2060. }
  2061. })
  2062. }),
  2063. // If the adapter indicates that there was an unknown
  2064. // error saving a record, the record enters the `error`
  2065. // state.
  2066. error: DS.State.create({
  2067. isError: true,
  2068. // EVENTS
  2069. invokeLifecycleCallbacks: function(manager) {
  2070. var record = get(manager, 'record');
  2071. record.trigger('becameError', record);
  2072. }
  2073. })
  2074. })
  2075. };
  2076. DS.StateManager = Ember.StateManager.extend({
  2077. record: null,
  2078. initialState: 'rootState',
  2079. states: states
  2080. });
  2081. })();
  2082. (function() {
  2083. var get = Ember.get, set = Ember.set;
  2084. // When a record is changed on the client, it is considered "dirty"--there are
  2085. // pending changes that need to be saved to a persistence layer, such as a
  2086. // server.
  2087. //
  2088. // If the record is rolled back, it re-enters a clean state, any changes are
  2089. // discarded, and its attributes are reset back to the last known good copy
  2090. // of the data that came from the server.
  2091. //
  2092. // If the record is committed, the changes are sent to the server to be saved,
  2093. // and once the server confirms that they are valid, the record's "canonical"
  2094. // data becomes the original canonical data plus the changes merged in.
  2095. //
  2096. // A DataProxy is an object that encapsulates this change tracking. It
  2097. // contains three buckets:
  2098. //
  2099. // * `savedData` - the last-known copy of the data from the server
  2100. // * `unsavedData` - a hash that contains any changes that have not yet
  2101. // been committed
  2102. // * `associations` - this is similar to `savedData`, but holds the client
  2103. // ids of associated records
  2104. //
  2105. // When setting a property on the object, the value is placed into the
  2106. // `unsavedData` bucket:
  2107. //
  2108. // proxy.set('key', 'value');
  2109. //
  2110. // // unsavedData:
  2111. // {
  2112. // key: "value"
  2113. // }
  2114. //
  2115. // When retrieving a property from the object, it first looks to see
  2116. // if that value exists in the `unsavedData` bucket, and returns it if so.
  2117. // Otherwise, it returns the value from the `savedData` bucket.
  2118. //
  2119. // When the adapter notifies a record that it has been saved, it merges the
  2120. // `unsavedData` bucket into the `savedData` bucket. If the record's
  2121. // transaction is rolled back, the `unsavedData` hash is simply discarded.
  2122. //
  2123. // This object is a regular JS object for performance. It is only
  2124. // used internally for bookkeeping purposes.
  2125. var DataProxy = DS._DataProxy = function(record) {
  2126. this.record = record;
  2127. this.unsavedData = {};
  2128. this.associations = {};
  2129. };
  2130. DataProxy.prototype = {
  2131. get: function(key) { return Ember.get(this, key); },
  2132. set: function(key, value) { return Ember.set(this, key, value); },
  2133. setAssociation: function(key, value) {
  2134. this.associations[key] = value;
  2135. },
  2136. savedData: function() {
  2137. var savedData = this._savedData;
  2138. if (savedData) { return savedData; }
  2139. var record = this.record,
  2140. clientId = get(record, 'clientId'),
  2141. store = get(record, 'store');
  2142. if (store) {
  2143. savedData = store.dataForRecord(record);
  2144. this._savedData = savedData;
  2145. return savedData;
  2146. }
  2147. },
  2148. unknownProperty: function(key) {
  2149. var unsavedData = this.unsavedData,
  2150. associations = this.associations,
  2151. savedData = this.savedData(),
  2152. store;
  2153. var value = unsavedData[key], association;
  2154. // if this is a belongsTo association, this will
  2155. // be a clientId.
  2156. association = associations[key];
  2157. if (association !== undefined) {
  2158. store = get(this.record, 'store');
  2159. return store.clientIdToId[association];
  2160. }
  2161. if (savedData && value === undefined) {
  2162. value = savedData[key];
  2163. }
  2164. return value;
  2165. },
  2166. setUnknownProperty: function(key, value) {
  2167. var record = this.record,
  2168. unsavedData = this.unsavedData;
  2169. unsavedData[key] = value;
  2170. record.hashWasUpdated();
  2171. return value;
  2172. },
  2173. commit: function() {
  2174. this.saveData();
  2175. this.record.notifyPropertyChange('data');
  2176. },
  2177. rollback: function() {
  2178. this.unsavedData = {};
  2179. this.record.notifyPropertyChange('data');
  2180. },
  2181. saveData: function() {
  2182. var record = this.record;
  2183. var unsavedData = this.unsavedData;
  2184. var savedData = this.savedData();
  2185. for (var prop in unsavedData) {
  2186. if (unsavedData.hasOwnProperty(prop)) {
  2187. savedData[prop] = unsavedData[prop];
  2188. delete unsavedData[prop];
  2189. }
  2190. }
  2191. },
  2192. adapterDidUpdate: function() {
  2193. this.unsavedData = {};
  2194. }
  2195. };
  2196. })();
  2197. (function() {
  2198. var get = Ember.get, set = Ember.set, none = Ember.none;
  2199. var retrieveFromCurrentState = Ember.computed(function(key) {
  2200. return get(get(this, 'stateManager.currentState'), key);
  2201. }).property('stateManager.currentState').cacheable();
  2202. DS.Model = Ember.Object.extend(Ember.Evented, {
  2203. isLoaded: retrieveFromCurrentState,
  2204. isDirty: retrieveFromCurrentState,
  2205. isSaving: retrieveFromCurrentState,
  2206. isDeleted: retrieveFromCurrentState,
  2207. isError: retrieveFromCurrentState,
  2208. isNew: retrieveFromCurrentState,
  2209. isPending: retrieveFromCurrentState,
  2210. isValid: retrieveFromCurrentState,
  2211. clientId: null,
  2212. transaction: null,
  2213. stateManager: null,
  2214. pendingQueue: null,
  2215. errors: null,
  2216. // because unknownProperty is used, any internal property
  2217. // must be initialized here.
  2218. primaryKey: 'id',
  2219. id: Ember.computed(function(key, value) {
  2220. var primaryKey = get(this, 'primaryKey'),
  2221. data = get(this, 'data');
  2222. if (arguments.length === 2) {
  2223. set(data, primaryKey, value);
  2224. return value;
  2225. }
  2226. var id = get(data, primaryKey);
  2227. return id ? id : this._id;
  2228. }).property('primaryKey', 'data'),
  2229. // The following methods are callbacks invoked by `toJSON`. You
  2230. // can override one of the callbacks to override specific behavior,
  2231. // or toJSON itself.
  2232. //
  2233. // If you override toJSON, you can invoke these callbacks manually
  2234. // to get the default behavior.
  2235. /**
  2236. Add the record's primary key to the JSON hash.
  2237. The default implementation uses the record's specified `primaryKey`
  2238. and the `id` computed property, which are passed in as parameters.
  2239. @param {Object} json the JSON hash being built
  2240. @param {Number|String} id the record's id
  2241. @param {String} key the primaryKey for the record
  2242. */
  2243. addIdToJSON: function(json, id, key) {
  2244. if (id) { json[key] = id; }
  2245. },
  2246. /**
  2247. Add the attributes' current values to the JSON hash.
  2248. The default implementation gets the current value of each
  2249. attribute from the `data`, and uses a `defaultValue` if
  2250. specified in the `DS.attr` definition.
  2251. @param {Object} json the JSON hash being build
  2252. @param {Ember.Map} attributes a Map of attributes
  2253. @param {DataProxy} data the record's data, accessed with `get` and `set`.
  2254. */
  2255. addAttributesToJSON: function(json, attributes, data) {
  2256. attributes.forEach(function(name, meta) {
  2257. var key = meta.key(this.constructor),
  2258. value = get(data, key);
  2259. if (value === undefined) {
  2260. value = meta.options.defaultValue;
  2261. }
  2262. json[key] = value;
  2263. }, this);
  2264. },
  2265. /**
  2266. Add the value of a `hasMany` association to the JSON hash.
  2267. The default implementation honors the `embedded` option
  2268. passed to `DS.hasMany`. If embedded, `toJSON` is recursively
  2269. called on the child records. If not, the `id` of each
  2270. record is added.
  2271. Note that if a record is not embedded and does not
  2272. yet have an `id` (usually provided by the server), it
  2273. will not be included in the output.
  2274. @param {Object} json the JSON hash being built
  2275. @param {DataProxy} data the record's data, accessed with `get` and `set`.
  2276. @param {Object} meta information about the association
  2277. @param {Object} options options passed to `toJSON`
  2278. */
  2279. addHasManyToJSON: function(json, data, meta, options) {
  2280. var key = meta.key,
  2281. manyArray = get(this, key),
  2282. records = [], i, l,
  2283. clientId, id;
  2284. if (meta.options.embedded) {
  2285. // TODO: Avoid materializing embedded hashes if possible
  2286. manyArray.forEach(function(record) {
  2287. records.push(record.toJSON(options));
  2288. });
  2289. } else {
  2290. var clientIds = get(manyArray, 'content');
  2291. for (i=0, l=clientIds.length; i<l; i++) {
  2292. clientId = clientIds[i];
  2293. id = get(this, 'store').clientIdToId[clientId];
  2294. if (id !== undefined) {
  2295. records.push(id);
  2296. }
  2297. }
  2298. }
  2299. key = meta.options.key || get(this, 'namingConvention').keyToJSONKey(key);
  2300. json[key] = records;
  2301. },
  2302. /**
  2303. Add the value of a `belongsTo` association to the JSON hash.
  2304. The default implementation always includes the `id`.
  2305. @param {Object} json the JSON hash being built
  2306. @param {DataProxy} data the record's data, accessed with `get` and `set`.
  2307. @param {Object} meta information about the association
  2308. @param {Object} options options passed to `toJSON`
  2309. */
  2310. addBelongsToToJSON: function(json, data, meta, options) {
  2311. var key = meta.key, value, id;
  2312. if (meta.options.embedded) {
  2313. key = meta.options.key || get(this, 'namingConvention').keyToJSONKey(key);
  2314. value = get(data.record, key);
  2315. json[key] = value ? value.toJSON(options) : null;
  2316. } else {
  2317. key = meta.options.key || get(this, 'namingConvention').foreignKey(key);
  2318. id = data.get(key);
  2319. json[key] = none(id) ? null : id;
  2320. }
  2321. },
  2322. /**
  2323. Create a JSON representation of the record, including its `id`,
  2324. attributes and associations. Honor any settings defined on the
  2325. attributes or associations (such as `embedded` or `key`).
  2326. */
  2327. toJSON: function(options) {
  2328. var data = get(this, 'data'),
  2329. result = {},
  2330. type = this.constructor,
  2331. attributes = get(type, 'attributes'),
  2332. primaryKey = get(this, 'primaryKey'),
  2333. id = get(this, 'id'),
  2334. store = get(this, 'store'),
  2335. associations;
  2336. options = options || {};
  2337. // delegate to `addIdToJSON` callback
  2338. this.addIdToJSON(result, id, primaryKey);
  2339. // delegate to `addAttributesToJSON` callback
  2340. this.addAttributesToJSON(result, attributes, data);
  2341. associations = get(type, 'associationsByName');
  2342. // add associations, delegating to `addHasManyToJSON` and
  2343. // `addBelongsToToJSON`.
  2344. associations.forEach(function(key, meta) {
  2345. if (options.associations && meta.kind === 'hasMany') {
  2346. this.addHasManyToJSON(result, data, meta, options);
  2347. } else if (meta.kind === 'belongsTo') {
  2348. this.addBelongsToToJSON(result, data, meta, options);
  2349. }
  2350. }, this);
  2351. return result;
  2352. },
  2353. data: Ember.computed(function() {
  2354. return new DS._DataProxy(this);
  2355. }).cacheable(),
  2356. didLoad: Ember.K,
  2357. didUpdate: Ember.K,
  2358. didCreate: Ember.K,
  2359. didDelete: Ember.K,
  2360. becameInvalid: Ember.K,
  2361. becameError: Ember.K,
  2362. init: function() {
  2363. var stateManager = DS.StateManager.create({
  2364. record: this
  2365. });
  2366. set(this, 'pendingQueue', {});
  2367. set(this, 'stateManager', stateManager);
  2368. stateManager.goToState('empty');
  2369. },
  2370. destroy: function() {
  2371. if (!get(this, 'isDeleted')) {
  2372. this.deleteRecord();
  2373. }
  2374. this._super();
  2375. },
  2376. send: function(name, context) {
  2377. return get(this, 'stateManager').send(name, context);
  2378. },
  2379. withTransaction: function(fn) {
  2380. var transaction = get(this, 'transaction');
  2381. if (transaction) { fn(transaction); }
  2382. },
  2383. setProperty: function(key, value) {
  2384. this.send('setProperty', { key: key, value: value });
  2385. },
  2386. deleteRecord: function() {
  2387. this.send('deleteRecord');
  2388. },
  2389. waitingOn: function(record) {
  2390. this.send('waitingOn', record);
  2391. },
  2392. notifyHashWasUpdated: function() {
  2393. var store = get(this, 'store');
  2394. if (store) {
  2395. store.hashWasUpdated(this.constructor, get(this, 'clientId'), this);
  2396. }
  2397. },
  2398. unknownProperty: function(key) {
  2399. var data = get(this, 'data');
  2400. if (data && key in data) {
  2401. Ember.assert("You attempted to access the " + key + " property on a record without defining an attribute.", false);
  2402. }
  2403. },
  2404. setUnknownProperty: function(key, value) {
  2405. var data = get(this, 'data');
  2406. if (data && key in data) {
  2407. Ember.assert("You attempted to set the " + key + " property on a record without defining an attribute.", false);
  2408. } else {
  2409. return this._super(key, value);
  2410. }
  2411. },
  2412. namingConvention: {
  2413. keyToJSONKey: function(key) {
  2414. // TODO: Strip off `is` from the front. Example: `isHipster` becomes `hipster`
  2415. return Ember.String.decamelize(key);
  2416. },
  2417. foreignKey: function(key) {
  2418. return Ember.String.decamelize(key) + '_id';
  2419. }
  2420. },
  2421. /** @private */
  2422. hashWasUpdated: function() {
  2423. // At the end of the run loop, notify record arrays that
  2424. // this record has changed so they can re-evaluate its contents
  2425. // to determine membership.
  2426. Ember.run.once(this, this.notifyHashWasUpdated);
  2427. },
  2428. dataDidChange: Ember.observer(function() {
  2429. var associations = get(this.constructor, 'associationsByName'),
  2430. data = get(this, 'data'), store = get(this, 'store'),
  2431. idToClientId = store.idToClientId,
  2432. cachedValue;
  2433. associations.forEach(function(name, association) {
  2434. if (association.kind === 'hasMany') {
  2435. cachedValue = this.cacheFor(name);
  2436. if (cachedValue) {
  2437. var key = association.options.key || get(this, 'namingConvention').keyToJSONKey(name),
  2438. ids = data.get(key) || [];
  2439. var clientIds;
  2440. if(association.options.embedded) {
  2441. clientIds = store.loadMany(association.type, ids).clientIds;
  2442. } else {
  2443. clientIds = Ember.EnumerableUtils.map(ids, function(id) {
  2444. return store.clientIdForId(association.type, id);
  2445. });
  2446. }
  2447. set(cachedValue, 'content', Ember.A(clientIds));
  2448. cachedValue.fetch();
  2449. }
  2450. }
  2451. }, this);
  2452. }, 'data'),
  2453. /**
  2454. @private
  2455. Override the default event firing from Ember.Evented to
  2456. also call methods with the given name.
  2457. */
  2458. trigger: function(name) {
  2459. Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
  2460. this._super.apply(this, arguments);
  2461. }
  2462. });
  2463. // Helper function to generate store aliases.
  2464. // This returns a function that invokes the named alias
  2465. // on the default store, but injects the class as the
  2466. // first parameter.
  2467. var storeAlias = function(methodName) {
  2468. return function() {
  2469. var store = get(DS, 'defaultStore'),
  2470. args = [].slice.call(arguments);
  2471. args.unshift(this);
  2472. return store[methodName].apply(store, args);
  2473. };
  2474. };
  2475. DS.Model.reopenClass({
  2476. isLoaded: storeAlias('recordIsLoaded'),
  2477. find: storeAlias('find'),
  2478. filter: storeAlias('filter'),
  2479. _create: DS.Model.create,
  2480. create: function() {
  2481. throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set.");
  2482. },
  2483. createRecord: storeAlias('createRecord')
  2484. });
  2485. })();
  2486. (function() {
  2487. var get = Ember.get;
  2488. DS.Model.reopenClass({
  2489. attributes: Ember.computed(function() {
  2490. var map = Ember.Map.create();
  2491. this.eachComputedProperty(function(name, meta) {
  2492. if (meta.isAttribute) { map.set(name, meta); }
  2493. });
  2494. return map;
  2495. }).cacheable(),
  2496. processAttributeKeys: function() {
  2497. if (this.processedAttributeKeys) { return; }
  2498. var namingConvention = this.proto().namingConvention;
  2499. this.eachComputedProperty(function(name, meta) {
  2500. if (meta.isAttribute && !meta.options.key) {
  2501. meta.options.key = namingConvention.keyToJSONKey(name, this);
  2502. }
  2503. }, this);
  2504. }
  2505. });
  2506. function getAttr(record, options, key) {
  2507. var data = get(record, 'data');
  2508. var value = get(data, key);
  2509. if (value === undefined) {
  2510. value = options.defaultValue;
  2511. }
  2512. return value;
  2513. }
  2514. DS.attr = function(type, options) {
  2515. var transform = DS.attr.transforms[type];
  2516. Ember.assert("Could not find model attribute of type " + type, !!transform);
  2517. var transformFrom = transform.from;
  2518. var transformTo = transform.to;
  2519. options = options || {};
  2520. var meta = {
  2521. type: type,
  2522. isAttribute: true,
  2523. options: options,
  2524. // this will ensure that the key always takes naming
  2525. // conventions into consideration.
  2526. key: function(recordType) {
  2527. recordType.processAttributeKeys();
  2528. return options.key;
  2529. }
  2530. };
  2531. return Ember.computed(function(key, value) {
  2532. var data;
  2533. key = meta.key(this.constructor);
  2534. if (arguments.length === 2) {
  2535. value = transformTo(value);
  2536. if (value !== getAttr(this, options, key)) {
  2537. this.setProperty(key, value);
  2538. }
  2539. } else {
  2540. value = getAttr(this, options, key);
  2541. }
  2542. return transformFrom(value);
  2543. // `data` is never set directly. However, it may be
  2544. // invalidated from the state manager's setData
  2545. // event.
  2546. }).property('data').cacheable().meta(meta);
  2547. };
  2548. DS.attr.transforms = {
  2549. string: {
  2550. from: function(serialized) {
  2551. return Ember.none(serialized) ? null : String(serialized);
  2552. },
  2553. to: function(deserialized) {
  2554. return Ember.none(deserialized) ? null : String(deserialized);
  2555. }
  2556. },
  2557. number: {
  2558. from: function(serialized) {
  2559. return Ember.none(serialized) ? null : Number(serialized);
  2560. },
  2561. to: function(deserialized) {
  2562. return Ember.none(deserialized) ? null : Number(deserialized);
  2563. }
  2564. },
  2565. 'boolean': {
  2566. from: function(serialized) {
  2567. return Boolean(serialized);
  2568. },
  2569. to: function(deserialized) {
  2570. return Boolean(deserialized);
  2571. }
  2572. },
  2573. date: {
  2574. from: function(serialized) {
  2575. var type = typeof serialized;
  2576. if (type === "string" || type === "number") {
  2577. return new Date(serialized);
  2578. } else if (serialized === null || serialized === undefined) {
  2579. // if the value is not present in the data,
  2580. // return undefined, not null.
  2581. return serialized;
  2582. } else {
  2583. return null;
  2584. }
  2585. },
  2586. to: function(date) {
  2587. if (date instanceof Date) {
  2588. var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  2589. var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  2590. var pad = function(num) {
  2591. return num < 10 ? "0"+num : ""+num;
  2592. };
  2593. var utcYear = date.getUTCFullYear(),
  2594. utcMonth = date.getUTCMonth(),
  2595. utcDayOfMonth = date.getUTCDate(),
  2596. utcDay = date.getUTCDay(),
  2597. utcHours = date.getUTCHours(),
  2598. utcMinutes = date.getUTCMinutes(),
  2599. utcSeconds = date.getUTCSeconds();
  2600. var dayOfWeek = days[utcDay];
  2601. var dayOfMonth = pad(utcDayOfMonth);
  2602. var month = months[utcMonth];
  2603. return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " +
  2604. pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT";
  2605. } else if (date === undefined) {
  2606. return undefined;
  2607. } else {
  2608. return null;
  2609. }
  2610. }
  2611. }
  2612. };
  2613. })();
  2614. (function() {
  2615. })();
  2616. (function() {
  2617. var get = Ember.get, set = Ember.set,
  2618. none = Ember.none;
  2619. var embeddedFindRecord = function(store, type, data, key, one) {
  2620. var association = get(data, key);
  2621. return none(association) ? undefined : store.load(type, association).id;
  2622. };
  2623. var referencedFindRecord = function(store, type, data, key, one) {
  2624. return get(data, key);
  2625. };
  2626. var hasAssociation = function(type, options, one) {
  2627. options = options || {};
  2628. var embedded = options.embedded,
  2629. findRecord = embedded ? embeddedFindRecord : referencedFindRecord;
  2630. var meta = { type: type, isAssociation: true, options: options, kind: 'belongsTo' };
  2631. return Ember.computed(function(key, value) {
  2632. var data = get(this, 'data'), ids, id, association,
  2633. store = get(this, 'store');
  2634. if (typeof type === 'string') {
  2635. type = get(this, type, false) || get(window, type);
  2636. }
  2637. if (arguments.length === 2) {
  2638. key = options.key || get(this, 'namingConvention').foreignKey(key);
  2639. this.send('setAssociation', { key: key, value: Ember.none(value) ? null : get(value, 'clientId') });
  2640. //data.setAssociation(key, get(value, 'clientId'));
  2641. // put the client id in `key` in the data hash
  2642. return value;
  2643. } else {
  2644. // Embedded belongsTo associations should not look for
  2645. // a foreign key.
  2646. if (embedded) {
  2647. key = options.key || get(this, 'namingConvention').keyToJSONKey(key);
  2648. // Non-embedded associations should look for a foreign key.
  2649. // For example, instead of person, we might look for person_id
  2650. } else {
  2651. key = options.key || get(this, 'namingConvention').foreignKey(key);
  2652. }
  2653. id = findRecord(store, type, data, key, true);
  2654. association = id ? store.find(type, id) : null;
  2655. }
  2656. return association;
  2657. }).property('data').cacheable().meta(meta);
  2658. };
  2659. DS.belongsTo = function(type, options) {
  2660. Ember.assert("The type passed to DS.belongsTo must be defined", !!type);
  2661. return hasAssociation(type, options);
  2662. };
  2663. })();
  2664. (function() {
  2665. var get = Ember.get, set = Ember.set;
  2666. var embeddedFindRecord = function(store, type, data, key) {
  2667. var association = get(data, key);
  2668. return association ? store.loadMany(type, association).ids : [];
  2669. };
  2670. var referencedFindRecord = function(store, type, data, key, one) {
  2671. return get(data, key);
  2672. };
  2673. var hasAssociation = function(type, options) {
  2674. options = options || {};
  2675. var embedded = options.embedded,
  2676. findRecord = embedded ? embeddedFindRecord : referencedFindRecord;
  2677. var meta = { type: type, isAssociation: true, options: options, kind: 'hasMany' };
  2678. return Ember.computed(function(key, value) {
  2679. var data = get(this, 'data'),
  2680. store = get(this, 'store'),
  2681. ids, id, association;
  2682. if (typeof type === 'string') {
  2683. type = get(this, type, false) || get(window, type);
  2684. }
  2685. key = options.key || get(this, 'namingConvention').keyToJSONKey(key);
  2686. ids = findRecord(store, type, data, key);
  2687. association = store.findMany(type, ids || []);
  2688. set(association, 'parentRecord', this);
  2689. return association;
  2690. }).property().cacheable().meta(meta);
  2691. };
  2692. DS.hasMany = function(type, options) {
  2693. Ember.assert("The type passed to DS.hasMany must be defined", !!type);
  2694. return hasAssociation(type, options);
  2695. };
  2696. })();
  2697. (function() {
  2698. var get = Ember.get;
  2699. DS.Model.reopenClass({
  2700. typeForAssociation: function(name) {
  2701. var association = get(this, 'associationsByName').get(name);
  2702. return association && association.type;
  2703. },
  2704. associations: Ember.computed(function() {
  2705. var map = Ember.Map.create();
  2706. this.eachComputedProperty(function(name, meta) {
  2707. if (meta.isAssociation) {
  2708. var type = meta.type,
  2709. typeList = map.get(type);
  2710. if (typeof type === 'string') {
  2711. type = get(this, type, false) || get(window, type);
  2712. meta.type = type;
  2713. }
  2714. if (!typeList) {
  2715. typeList = [];
  2716. map.set(type, typeList);
  2717. }
  2718. typeList.push({ name: name, kind: meta.kind });
  2719. }
  2720. });
  2721. return map;
  2722. }).cacheable(),
  2723. associationsByName: Ember.computed(function() {
  2724. var map = Ember.Map.create(), type;
  2725. this.eachComputedProperty(function(name, meta) {
  2726. if (meta.isAssociation) {
  2727. meta.key = name;
  2728. type = meta.type;
  2729. if (typeof type === 'string') {
  2730. type = get(this, type, false) || get(window, type);
  2731. meta.type = type;
  2732. }
  2733. map.set(name, meta);
  2734. }
  2735. });
  2736. return map;
  2737. }).cacheable()
  2738. });
  2739. })();
  2740. (function() {
  2741. })();
  2742. (function() {
  2743. /**
  2744. An adapter is an object that receives requests from a store and
  2745. translates them into the appropriate action to take against your
  2746. persistence layer. The persistence layer is usually an HTTP API, but may
  2747. be anything, such as the browser's local storage.
  2748. ### Creating an Adapter
  2749. First, create a new subclass of `DS.Adapter`:
  2750. App.MyAdapter = DS.Adapter.extend({
  2751. // ...your code here
  2752. });
  2753. To tell your store which adapter to use, set its `adapter` property:
  2754. App.store = DS.Store.create({
  2755. revision: 3,
  2756. adapter: App.MyAdapter.create()
  2757. });
  2758. `DS.Adapter` is an abstract base class that you should override in your
  2759. application to customize it for your backend. The minimum set of methods
  2760. that you should implement is:
  2761. * `find()`
  2762. * `createRecord()`
  2763. * `updateRecord()`
  2764. * `deleteRecord()`
  2765. To improve the network performance of your application, you can optimize
  2766. your adapter by overriding these lower-level methods:
  2767. * `findMany()`
  2768. * `createRecords()`
  2769. * `updateRecords()`
  2770. * `deleteRecords()`
  2771. * `commit()`
  2772. For more information about the adapter API, please see `README.md`.
  2773. */
  2774. DS.Adapter = Ember.Object.extend({
  2775. /**
  2776. The `find()` method is invoked when the store is asked for a record that
  2777. has not previously been loaded. In response to `find()` being called, you
  2778. should query your persistence layer for a record with the given ID. Once
  2779. found, you can asynchronously call the store's `load()` method to load
  2780. the record.
  2781. Here is an example `find` implementation:
  2782. find: function(store, type, id) {
  2783. var url = type.url;
  2784. url = url.fmt(id);
  2785. jQuery.getJSON(url, function(data) {
  2786. // data is a Hash of key/value pairs. If your server returns a
  2787. // root, simply do something like:
  2788. // store.load(type, id, data.person)
  2789. store.load(type, id, data);
  2790. });
  2791. }
  2792. */
  2793. find: null,
  2794. /**
  2795. If the globally unique IDs for your records should be generated on the client,
  2796. implement the `generateIdForRecord()` method. This method will be invoked
  2797. each time you create a new record, and the value returned from it will be
  2798. assigned to the record's `primaryKey`.
  2799. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
  2800. of the record will be set by the server, and your adapter will update the store
  2801. with the new ID when it calls `didCreateRecord()`. Only implement this method if
  2802. you intend to generate record IDs on the client-side.
  2803. The `generateIdForRecord()` method will be invoked with the requesting store as
  2804. the first parameter and the newly created record as the second parameter:
  2805. generateIdForRecord: function(store, record) {
  2806. var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
  2807. return uuid;
  2808. }
  2809. */
  2810. generateIdForRecord: null,
  2811. commit: function(store, commitDetails) {
  2812. commitDetails.updated.eachType(function(type, array) {
  2813. this.updateRecords(store, type, array.slice());
  2814. }, this);
  2815. commitDetails.created.eachType(function(type, array) {
  2816. this.createRecords(store, type, array.slice());
  2817. }, this);
  2818. commitDetails.deleted.eachType(function(type, array) {
  2819. this.deleteRecords(store, type, array.slice());
  2820. }, this);
  2821. },
  2822. createRecords: function(store, type, records) {
  2823. records.forEach(function(record) {
  2824. this.createRecord(store, type, record);
  2825. }, this);
  2826. },
  2827. updateRecords: function(store, type, records) {
  2828. records.forEach(function(record) {
  2829. this.updateRecord(store, type, record);
  2830. }, this);
  2831. },
  2832. deleteRecords: function(store, type, records) {
  2833. records.forEach(function(record) {
  2834. this.deleteRecord(store, type, record);
  2835. }, this);
  2836. },
  2837. findMany: function(store, type, ids) {
  2838. ids.forEach(function(id) {
  2839. this.find(store, type, id);
  2840. }, this);
  2841. }
  2842. });
  2843. })();
  2844. (function() {
  2845. var set = Ember.set;
  2846. Ember.onLoad('application', function(app) {
  2847. app.registerInjection({
  2848. name: "store",
  2849. before: "controllers",
  2850. injection: function(app, stateManager, property) {
  2851. if (property === 'Store') {
  2852. set(stateManager, 'store', app[property].create());
  2853. }
  2854. }
  2855. });
  2856. app.registerInjection({
  2857. name: "giveStoreToControllers",
  2858. injection: function(app, stateManager, property) {
  2859. if (property.match(/Controller$/)) {
  2860. var controllerName = property.charAt(0).toLowerCase() + property.substr(1);
  2861. var store = stateManager.get('store');
  2862. var controller = stateManager.get(controllerName);
  2863. controller.set('store', store);
  2864. }
  2865. }
  2866. });
  2867. });
  2868. })();
  2869. (function() {
  2870. var get = Ember.get;
  2871. DS.FixtureAdapter = DS.Adapter.extend({
  2872. simulateRemoteResponse: true,
  2873. latency: 50,
  2874. /*
  2875. Implement this method in order to provide data associated with a type
  2876. */
  2877. fixturesForType: function(type) {
  2878. return type.FIXTURES ? Ember.A(type.FIXTURES) : null;
  2879. },
  2880. /*
  2881. Implement this method in order to query fixtures data
  2882. */
  2883. queryFixtures: function(fixtures, query) {
  2884. return fixtures;
  2885. },
  2886. /*
  2887. Implement this method in order to provide provide json for CRUD methods
  2888. */
  2889. mockJSON: function(type, record) {
  2890. return record.toJSON({associations: true});
  2891. },
  2892. /*
  2893. Adapter methods
  2894. */
  2895. generateIdForRecord: function(store, record) {
  2896. return Ember.guidFor(record);
  2897. },
  2898. find: function(store, type, id) {
  2899. var fixtures = this.fixturesForType(type);
  2900. Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
  2901. if (fixtures) {
  2902. fixtures = fixtures.findProperty('id', id);
  2903. }
  2904. if (fixtures) {
  2905. this.simulateRemoteCall(function() {
  2906. store.load(type, fixtures);
  2907. }, store, type);
  2908. }
  2909. },
  2910. findMany: function(store, type, ids) {
  2911. var fixtures = this.fixturesForType(type);
  2912. Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
  2913. if (fixtures) {
  2914. fixtures = fixtures.filter(function(item) {
  2915. return ids.indexOf(item.id) !== -1;
  2916. });
  2917. }
  2918. if (fixtures) {
  2919. this.simulateRemoteCall(function() {
  2920. store.loadMany(type, fixtures);
  2921. }, store, type);
  2922. }
  2923. },
  2924. findAll: function(store, type) {
  2925. var fixtures = this.fixturesForType(type);
  2926. Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
  2927. this.simulateRemoteCall(function() {
  2928. store.loadMany(type, fixtures);
  2929. }, store, type);
  2930. },
  2931. findQuery: function(store, type, query, array) {
  2932. var fixtures = this.fixturesForType(type);
  2933. Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
  2934. fixtures = this.queryFixtures(fixtures, query);
  2935. if (fixtures) {
  2936. this.simulateRemoteCall(function() {
  2937. array.load(fixtures);
  2938. }, store, type);
  2939. }
  2940. },
  2941. createRecord: function(store, type, record) {
  2942. var fixture = this.mockJSON(type, record);
  2943. fixture.id = this.generateIdForRecord(store, record);
  2944. this.simulateRemoteCall(function() {
  2945. store.didCreateRecord(record, fixture);
  2946. }, store, type, record);
  2947. },
  2948. updateRecord: function(store, type, record) {
  2949. var fixture = this.mockJSON(type, record);
  2950. this.simulateRemoteCall(function() {
  2951. store.didUpdateRecord(record, fixture);
  2952. }, store, type, record);
  2953. },
  2954. deleteRecord: function(store, type, record) {
  2955. this.simulateRemoteCall(function() {
  2956. store.didDeleteRecord(record);
  2957. }, store, type, record);
  2958. },
  2959. /*
  2960. @private
  2961. */
  2962. simulateRemoteCall: function(callback, store, type, record) {
  2963. if (get(this, 'simulateRemoteResponse')) {
  2964. setTimeout(callback, get(this, 'latency'));
  2965. } else {
  2966. callback();
  2967. }
  2968. }
  2969. });
  2970. DS.fixtureAdapter = DS.FixtureAdapter.create();
  2971. })();
  2972. (function() {
  2973. /*global jQuery*/
  2974. var get = Ember.get, set = Ember.set;
  2975. DS.RESTAdapter = DS.Adapter.extend({
  2976. bulkCommit: false,
  2977. createRecord: function(store, type, record) {
  2978. var root = this.rootForType(type);
  2979. var data = {};
  2980. data[root] = record.toJSON();
  2981. this.ajax(this.buildURL(root), "POST", {
  2982. data: data,
  2983. context: this,
  2984. success: function(json) {
  2985. this.didCreateRecord(store, type, record, json);
  2986. }
  2987. });
  2988. },
  2989. didCreateRecord: function(store, type, record, json) {
  2990. var root = this.rootForType(type);
  2991. this.sideload(store, type, json, root);
  2992. store.didCreateRecord(record, json[root]);
  2993. },
  2994. createRecords: function(store, type, records) {
  2995. if (get(this, 'bulkCommit') === false) {
  2996. return this._super(store, type, records);
  2997. }
  2998. var root = this.rootForType(type),
  2999. plural = this.pluralize(root);
  3000. var data = {};
  3001. data[plural] = records.map(function(record) {
  3002. return record.toJSON();
  3003. });
  3004. this.ajax(this.buildURL(root), "POST", {
  3005. data: data,
  3006. context: this,
  3007. success: function(json) {
  3008. this.didCreateRecords(store, type, records, json);
  3009. }
  3010. });
  3011. },
  3012. didCreateRecords: function(store, type, records, json) {
  3013. var root = this.pluralize(this.rootForType(type));
  3014. this.sideload(store, type, json, root);
  3015. store.didCreateRecords(type, records, json[root]);
  3016. },
  3017. updateRecord: function(store, type, record) {
  3018. var id = get(record, 'id');
  3019. var root = this.rootForType(type);
  3020. var data = {};
  3021. data[root] = record.toJSON();
  3022. this.ajax(this.buildURL(root, id), "PUT", {
  3023. data: data,
  3024. context: this,
  3025. success: function(json) {
  3026. this.didUpdateRecord(store, type, record, json);
  3027. }
  3028. });
  3029. },
  3030. didUpdateRecord: function(store, type, record, json) {
  3031. var root = this.rootForType(type);
  3032. this.sideload(store, type, json, root);
  3033. store.didUpdateRecord(record, json && json[root]);
  3034. },
  3035. updateRecords: function(store, type, records) {
  3036. if (get(this, 'bulkCommit') === false) {
  3037. return this._super(store, type, records);
  3038. }
  3039. var root = this.rootForType(type),
  3040. plural = this.pluralize(root);
  3041. var data = {};
  3042. data[plural] = records.map(function(record) {
  3043. return record.toJSON();
  3044. });
  3045. this.ajax(this.buildURL(root, "bulk"), "PUT", {
  3046. data: data,
  3047. context: this,
  3048. success: function(json) {
  3049. this.didUpdateRecords(store, type, records, json);
  3050. }
  3051. });
  3052. },
  3053. didUpdateRecords: function(store, type, records, json) {
  3054. var root = this.pluralize(this.rootForType(type));
  3055. this.sideload(store, type, json, root);
  3056. store.didUpdateRecords(records, json[root]);
  3057. },
  3058. deleteRecord: function(store, type, record) {
  3059. var id = get(record, 'id');
  3060. var root = this.rootForType(type);
  3061. this.ajax(this.buildURL(root, id), "DELETE", {
  3062. context: this,
  3063. success: function(json) {
  3064. this.didDeleteRecord(store, type, record, json);
  3065. }
  3066. });
  3067. },
  3068. didDeleteRecord: function(store, type, record, json) {
  3069. if (json) { this.sideload(store, type, json); }
  3070. store.didDeleteRecord(record);
  3071. },
  3072. deleteRecords: function(store, type, records) {
  3073. if (get(this, 'bulkCommit') === false) {
  3074. return this._super(store, type, records);
  3075. }
  3076. var root = this.rootForType(type),
  3077. plural = this.pluralize(root);
  3078. var data = {};
  3079. data[plural] = records.map(function(record) {
  3080. return get(record, 'id');
  3081. });
  3082. this.ajax(this.buildURL(root, 'bulk'), "DELETE", {
  3083. data: data,
  3084. context: this,
  3085. success: function(json) {
  3086. this.didDeleteRecords(store, type, records, json);
  3087. }
  3088. });
  3089. },
  3090. didDeleteRecords: function(store, type, records, json) {
  3091. if (json) { this.sideload(store, type, json); }
  3092. store.didDeleteRecords(records);
  3093. },
  3094. find: function(store, type, id) {
  3095. var root = this.rootForType(type);
  3096. this.ajax(this.buildURL(root, id), "GET", {
  3097. success: function(json) {
  3098. this.sideload(store, type, json, root);
  3099. store.load(type, json[root]);
  3100. }
  3101. });
  3102. },
  3103. findMany: function(store, type, ids) {
  3104. var root = this.rootForType(type), plural = this.pluralize(root);
  3105. this.ajax(this.buildURL(root), "GET", {
  3106. data: { ids: ids },
  3107. success: function(json) {
  3108. this.sideload(store, type, json, plural);
  3109. store.loadMany(type, json[plural]);
  3110. }
  3111. });
  3112. },
  3113. findAll: function(store, type) {
  3114. var root = this.rootForType(type), plural = this.pluralize(root);
  3115. this.ajax(this.buildURL(root), "GET", {
  3116. success: function(json) {
  3117. this.sideload(store, type, json, plural);
  3118. store.loadMany(type, json[plural]);
  3119. }
  3120. });
  3121. },
  3122. findQuery: function(store, type, query, recordArray) {
  3123. var root = this.rootForType(type), plural = this.pluralize(root);
  3124. this.ajax(this.buildURL(root), "GET", {
  3125. data: query,
  3126. success: function(json) {
  3127. this.sideload(store, type, json, plural);
  3128. recordArray.load(json[plural]);
  3129. }
  3130. });
  3131. },
  3132. // HELPERS
  3133. plurals: {},
  3134. // define a plurals hash in your subclass to define
  3135. // special-case pluralization
  3136. pluralize: function(name) {
  3137. return this.plurals[name] || name + "s";
  3138. },
  3139. rootForType: function(type) {
  3140. if (type.url) { return type.url; }
  3141. // use the last part of the name as the URL
  3142. var parts = type.toString().split(".");
  3143. var name = parts[parts.length - 1];
  3144. return name.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1);
  3145. },
  3146. ajax: function(url, type, hash) {
  3147. hash.url = url;
  3148. hash.type = type;
  3149. hash.dataType = 'json';
  3150. hash.contentType = 'application/json; charset=utf-8';
  3151. hash.context = this;
  3152. if (hash.data && type !== 'GET') {
  3153. hash.data = JSON.stringify(hash.data);
  3154. }
  3155. jQuery.ajax(hash);
  3156. },
  3157. sideload: function(store, type, json, root) {
  3158. var sideloadedType, mappings, loaded = {};
  3159. loaded[root] = true;
  3160. for (var prop in json) {
  3161. if (!json.hasOwnProperty(prop)) { continue; }
  3162. if (prop === root) { continue; }
  3163. sideloadedType = type.typeForAssociation(prop);
  3164. if (!sideloadedType) {
  3165. mappings = get(this, 'mappings');
  3166. Ember.assert("Your server returned a hash with the key " + prop + " but you have no mappings", !!mappings);
  3167. sideloadedType = get(mappings, prop);
  3168. if (typeof sideloadedType === 'string') {
  3169. sideloadedType = get(window, sideloadedType);
  3170. }
  3171. Ember.assert("Your server returned a hash with the key " + prop + " but you have no mapping for it", !!sideloadedType);
  3172. }
  3173. this.sideloadAssociations(store, sideloadedType, json, prop, loaded);
  3174. }
  3175. },
  3176. sideloadAssociations: function(store, type, json, prop, loaded) {
  3177. loaded[prop] = true;
  3178. get(type, 'associationsByName').forEach(function(key, meta) {
  3179. key = meta.key || key;
  3180. if (meta.kind === 'belongsTo') {
  3181. key = this.pluralize(key);
  3182. }
  3183. if (json[key] && !loaded[key]) {
  3184. this.sideloadAssociations(store, meta.type, json, key, loaded);
  3185. }
  3186. }, this);
  3187. this.loadValue(store, type, json[prop]);
  3188. },
  3189. loadValue: function(store, type, value) {
  3190. if (value instanceof Array) {
  3191. store.loadMany(type, value);
  3192. } else {
  3193. store.load(type, value);
  3194. }
  3195. },
  3196. buildURL: function(record, suffix) {
  3197. var url = [""];
  3198. Ember.assert("Namespace URL (" + this.namespace + ") must not start with slash", !this.namespace || this.namespace.toString().charAt(0) !== "/");
  3199. Ember.assert("Record URL (" + record + ") must not start with slash", !record || record.toString().charAt(0) !== "/");
  3200. Ember.assert("URL suffix (" + suffix + ") must not start with slash", !suffix || suffix.toString().charAt(0) !== "/");
  3201. if (this.namespace !== undefined) {
  3202. url.push(this.namespace);
  3203. }
  3204. url.push(this.pluralize(record));
  3205. if (suffix !== undefined) {
  3206. url.push(suffix);
  3207. }
  3208. return url.join("/");
  3209. }
  3210. });
  3211. })();
  3212. (function() {
  3213. //Copyright (C) 2011 by Living Social, Inc.
  3214. //Permission is hereby granted, free of charge, to any person obtaining a copy of
  3215. //this software and associated documentation files (the "Software"), to deal in
  3216. //the Software without restriction, including without limitation the rights to
  3217. //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  3218. //of the Software, and to permit persons to whom the Software is furnished to do
  3219. //so, subject to the following conditions:
  3220. //The above copyright notice and this permission notice shall be included in all
  3221. //copies or substantial portions of the Software.
  3222. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3223. //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3224. //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3225. //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3226. //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3227. //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  3228. //SOFTWARE.
  3229. })();