forked from canjs/canjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.js
1607 lines (1561 loc) · 51.1 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// this file should not be stolen directly
steal('can/util','can/observe', function( can ) {
// ## model.js
// `can.Model`
// _A `can.Observe` that connects to a RESTful interface._
//
// Generic deferred piping function
/**
* @add can.Model
*/
var pipe = function( def, model, func ) {
var d = new can.Deferred();
def.then(function(){
var args = can.makeArray( arguments ),
success = true;
try {
args[0] = model[func](args[0]);
} catch(e) {
success = false;
d.rejectWith(d, [e].concat(args));
}
if (success) {
d.resolveWith(d, args);
}
},function(){
d.rejectWith(this, arguments);
});
if(typeof def.abort === 'function') {
d.abort = function() {
return def.abort();
}
}
return d;
},
modelNum = 0,
ignoreHookup = /change.observe\d+/,
getId = function( inst ) {
// Instead of using attr, use __get for performance.
// Need to set reading
can.Observe.__reading && can.Observe.__reading(inst, inst.constructor.id)
return inst.__get(inst.constructor.id);
},
// Ajax `options` generator function
ajax = function( ajaxOb, data, type, dataType, success, error ) {
var params = {};
// If we get a string, handle it.
if ( typeof ajaxOb == "string" ) {
// If there's a space, it's probably the type.
var parts = ajaxOb.split(/\s+/);
params.url = parts.pop();
if ( parts.length ) {
params.type = parts.pop();
}
} else {
can.extend( params, ajaxOb );
}
// If we are a non-array object, copy to a new attrs.
params.data = typeof data == "object" && ! can.isArray( data ) ?
can.extend(params.data || {}, data) : data;
// Get the url with any templated values filled out.
params.url = can.sub(params.url, params.data, true);
return can.ajax( can.extend({
type: type || "post",
dataType: dataType ||"json",
success : success,
error: error
}, params ));
},
makeRequest = function( self, type, success, error, method ) {
var args;
// if we pass an array as `self` it it means we are coming from
// the queued request, and we're passing already serialized data
// self's signature will be: [self, serializedData]
if(can.isArray(self)){
args = self[1];
self = self[0];
} else {
args = self.serialize();
}
args = [args];
var deferred,
// The model.
model = self.constructor,
jqXHR;
// `destroy` does not need data.
if ( type == 'destroy' ) {
args.shift();
}
// `update` and `destroy` need the `id`.
if ( type !== 'create' ) {
args.unshift(getId(self));
}
jqXHR = model[type].apply(model, args);
deferred = jqXHR.pipe(function(data){
self[method || type + "d"](data, jqXHR);
return self;
});
// Hook up `abort`
if(jqXHR.abort){
deferred.abort = function(){
jqXHR.abort();
};
}
deferred.then(success,error);
return deferred;
},
// This object describes how to make an ajax request for each ajax method.
// The available properties are:
// `url` - The default url to use as indicated as a property on the model.
// `type` - The default http request type
// `data` - A method that takes the `arguments` and returns `data` used for ajax.
/**
* @static
*/
//
/**
* @function can.Model.bind bind
* @parent can.Model.static
* @description Listen for events on a Model class.
*
* @signature `can.Model.bind(eventType, handler)`
* @param {String} eventType The type of event. It must be
* `"created"`, `"udpated"`, `"destroyed"`.
* @param {function} handler A callback function
* that gets called with the event and instance that was
* created, destroyed, or updated.
* @return {can.Model} The model constructor function.
*
* @body
* `bind(eventType, handler(event, instance))` listens to
* __created__, __updated__, __destroyed__ events on all
* instances of the model.
*
* Task.bind("created", function(ev, createdTask){
* this //-> Task
* createdTask.attr("name") //-> "Dishes"
* })
*
* new Task({name: "Dishes"}).save();
*/
//
/**
* @function can.Model.unbind unbind
* @parent can.Model.static
* @description Stop listening for events on a Model class.
*
* @signature `can.Model.unbind(eventType, handler)`
* @param {String} eventType The type of event. It must be
* `"created"`, `"udpated"`, `"destroyed"`.
* @param {function} handler A callback function
* that was passed to `bind`.
* @return {can.Model} The model constructor function.
*
* @body
* `unbind(eventType, handler)` removes a listener
* attached with [can.Model.bind].
*
* var handler = function(ev, createdTask){
*
* }
* Task.bind("created", handler)
* Task.unbind("created", handler)
*
* You have to pass the same function to `unbind` that you
* passed to `bind`.
*/
//
/**
* @property {String} can.Model.id id
* @parent can.Model.static
* The name of the id field. Defaults to `'id'`. Change this if it is something different.
*
* For example, it's common in .NET to use `'Id'`. Your model might look like:
*
* Friend = can.Model.extend({
* id: "Id"
* },{});
*/
/**
* @property {Boolean} can.Model.removeAttr removeAttr
* @parent can.Model.static
* Sets whether model conversion should remove non existing attributes or merge with
* the existing attributes. The default is `false`.
* For example, if `Task.findOne({ id: 1 })` returns
*
* { id: 1, name: 'Do dishes', index: 1, color: ['red', 'blue'] }
*
* for the first request and
*
* { id: 1, name: 'Really do dishes', color: ['green'] }
*
* for the next request, the actual model attributes would look like:
*
* { id: 1, name: 'Really do dishes', index: 1, color: ['green', 'blue'] }
*
* Because the attributes of the original model and the updated model will
* be merged. Setting `removeAttr` to `true` will result in model attributes like
*
* { id: 1, name: 'Really do dishes', color: ['green'] }
*
*/
ajaxMethods = {
/**
* @description Specifies how to create a new resource on the server. `create(serialized)` is called
* by [can.Model.prototype.save save] if the model instance [can.Model.prototype.isNew is new].
* @function can.Model.create create
* @parent can.Model.static
*
*
* @signature `can.Model.create: function(serialized) -> seferred`
*
* Specify a function to create persistent instances. The function will
* typically perform an AJAX request to a service that results in
* creating a record in a database.
*
* @param {Object} serialized The [can.Observe::serialize serialized] properties of
* the model to create.
* @return {can.Deferred} A Deferred that resolves to an object of attributes
* that will be added to the created model isntance. The object __MUST__ contain
* an [can.Model.id id] property so that future calls to [can.Model.prototype.save save]
* will call [can.Model.update].
*
*
* @signature `can.Model.create: "[METHOD] /path/to/resource"`
*
* Specify a HTTP method and url to create persistent instances.
*
* If you provide a URL, the Model will send a request to that URL using
* the method specified (or POST if none is specified) when saving a
* new instance on the server. (See below for more details.)
*
* @param {HttpMethod} METHOD An HTTP method. Defaults to `"POST"`.
* @param {STRING} url The URL of the service to retrieve JSON data.
*
*
* @signature `can.Model.create: {ajaxSettings}`
*
* Specify an options object that is used to make a HTTP request to create
* persistent instances.
*
* @param {can.AjaxSettings} ajaxSettings A settings object that
* specifies the options available to pass to [can.ajax].
*
* @body
*
* `create(attributes) -> Deferred` is used by [can.Model::save save] to create a
* model instance on the server.
*
* ## Implement with a URL
*
* The easiest way to implement create is to give it the url
* to post data to:
*
* var Recipe = can.Model.extend({
* create: "/recipes"
* },{})
*
* This lets you create a recipe like:
*
* new Recipe({name: "hot dog"}).save();
*
*
* ## Implement with a Function
*
* You can also implement create by yourself. Create gets called
* with `attrs`, which are the [can.Observe::serialize serialized] model
* attributes. Create returns a `Deferred`
* that contains the id of the new instance and any other
* properties that should be set on the instance.
*
* For example, the following code makes a request
* to `POST /recipes.json {'name': 'hot+dog'}` and gets back
* something that looks like:
*
* {
* "id": 5,
* "createdAt": 2234234329
* }
*
* The code looks like:
*
* can.Model.extend("Recipe", {
* create : function( attrs ){
* return $.post("/recipes.json",attrs, undefined ,"json");
* }
* },{})
*/
create : {
url : "_shortName",
type :"post"
},
/**
* @description Update a resource on the server.
* @function can.Model.update update
* @parent can.Model.static
* @signature `can.Model.update: "[METHOD] /path/to/resource"`
* If you provide a URL, the Model will send a request to that URL using
* the method specified (or PUT if none is specified) when updating an
* instance on the server. (See below for more details.)
* @return {can.Deferred} A Deferred that resolves to the updated model.
*
* @signature `can.Model.update: function(id, serialized) -> can.Deffered`
* If you provide a function, the Model will expect you to do your own AJAX requests.
* @param {*} id The ID of the model to update.
* @param {Object} serialized The [can.Observe::serialize serialized] properties of
* the model to update.
* @return {can.Deferred} A Deferred that resolves to the updated model.
*
* @body
* `update( id, attrs ) -> Deferred` is used by [can.Model::save save] to
* update a model instance on the server.
*
* ## Implement with a URL
*
* The easist way to implement update is to just give it the url to `PUT` data to:
*
* Recipe = can.Model.extend({
* update: "/recipes/{id}"
* },{});
*
* This lets you update a recipe like:
*
* Recipe.findOne({id: 1}, function(recipe){
* recipe.attr('name','salad');
* recipe.save();
* })
*
* This will make an XHR request like:
*
* PUT /recipes/1
* name=salad
*
* If your server doesn't use PUT, you can change it to post like:
*
* Recipe = can.Model.extend({
* update: "POST /recipes/{id}"
* },{});
*
* The server should send back an object with any new attributes the model
* should have. For example if your server udpates the "updatedAt" property, it
* should send back something like:
*
* // PUT /recipes/4 {name: "Food"} ->
* {
* updatedAt : "10-20-2011"
* }
*
* ## Implement with a Function
*
* You can also implement update by yourself. Update takes the `id` and
* `attributes` of the instance to be udpated. Update must return
* a [can.Deferred Deferred] that resolves to an object that contains any
* properties that should be set on the instance.
*
* For example, the following code makes a request
* to '/recipes/5.json?name=hot+dog' and gets back
* something that looks like:
*
* {
* updatedAt: "10-20-2011"
* }
*
* The code looks like:
*
* Recipe = can.Model.extend({
* update : function(id, attrs ) {
* return $.post("/recipes/"+id+".json",attrs, null,"json");
* }
* },{});
*/
update : {
data : function(id, attrs){
attrs = attrs || {};
var identity = this.id;
if ( attrs[identity] && attrs[identity] !== id ) {
attrs["new" + can.capitalize(id)] = attrs[identity];
delete attrs[identity];
}
attrs[identity] = id;
return attrs;
},
type : "put"
},
/**
* @description Destroy a resource on the server.
* @function can.Model.destroy destroy
* @parent can.Model.static
*
* @signature `can.Model.destroy: function(id) -> deferred`
*
*
*
* If you provide a function, the Model will expect you to do your own AJAX requests.
* @param {*} id The ID of the resource to destroy.
* @return {can.Deferred} A Deferred that resolves to the destroyed model.
*
*
* @signature `can.Model.destroy: "[METHOD] /path/to/resource"`
*
* If you provide a URL, the Model will send a request to that URL using
* the method specified (or DELETE if none is specified) when deleting an
* instance on the server. (See below for more details.)
*
* @return {can.Deferred} A Deferred that resolves to the destroyed model.
*
*
*
* @body
* `destroy(id) -> Deferred` is used by [can.Model::destroy] remove a model
* instance from the server.
*
* ## Implement with a URL
*
* You can implement destroy with a string like:
*
* Recipe = can.Model.extend({
* destroy : "/recipe/{id}"
* },{})
*
* And use [can.Model::destroy] to destroy it like:
*
* Recipe.findOne({id: 1}, function(recipe){
* recipe.destroy();
* });
*
* This sends a `DELETE` request to `/thing/destroy/1`.
*
* If your server does not support `DELETE` you can override it like:
*
* Recipe = can.Model.extend({
* destroy : "POST /recipe/destroy/{id}"
* },{})
*
* ## Implement with a function
*
* Implement destroy with a function like:
*
* Recipe = can.Model.extend({
* destroy : function(id){
* return $.post("/recipe/destroy/"+id,{});
* }
* },{})
*
* Destroy just needs to return a deferred that resolves.
*/
destroy : {
type : "delete",
data : function(id){
var args = {};
args.id = args[this.id] = id;
return args;
}
},
/**
* @description Retrieve multiple resources from a server.
* @function can.Model.findAll findAll
* @parent can.Model.static
*
* @signature `can.Model.findAll( params[, success[, error]] )`
*
* Retrieve multiple resources from a server.
*
* @param {Object} params Values to filter the request or results with.
* @param {function(can.Model.List)} [success(list)] A callback to call on successful retrieval. The callback recieves
* a can.Model.List of the retrieved resources.
* @param {function(can.AjaxSettings)} [error(xhr)] A callback to call when an error occurs. The callback receives the
* XmlHttpRequest object.
* @return {can.Deferred} A deferred that resolves to a [can.Model.List] of retrieved models.
*
*
* @signature `can.Model.findAll: findAllData( params ) -> deferred`
*
* Implements `findAll` with a [can.Model.findAllData function]. This function
* is passed to [can.Model.makeFindAll makeFindAll] to create the external
* `findAll` method.
*
* findAll: function(params){
* return $.get("/tasks",params)
* }
*
* @param {can.Model.findAllData} findAllData A function that accepts parameters
* specifying a list of instance data to retreive and returns a [can.Deferred]
* that resolves to an array of those instances.
*
* @signature `can.Model.findAll: "[METHOD] /path/to/resource"`
*
* Implements `findAll` with a HTTP method and url to retrieve instance data.
*
* findAll: "GET /tasks"
*
* If `findAll` is implemented with a string, this gets converted to
* a [can.Model.findAllData findAllData function]
* which is passed to [can.Model.makeFindAll makeFindAll] to create the external
* `findAll` method.
*
* @param {HttpMethod} METHOD An HTTP method. Defaults to `"GET"`.
*
* @param {STRING} url The URL of the service to retrieve JSON data.
*
* @return {JSON} The service should return a JSON object like:
*
* {
* "data": [
* { "id" : 1, "name" : "do the dishes" },
* { "id" : 2, "name" : "mow the lawn" },
* { "id" : 3, "name" : "iron my shirts" }
* ]
* }
*
* This object is passed to [can.Model.models] to turn it into instances.
*
* _Note: .findAll can also accept an array, but you
* probably [should not be doing that](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)._
*
*
* @signature `can.Model.findAll: {ajaxSettings}`
*
* Implements `findAll` with a [can.AjaxSettings ajax settings object].
*
* findAll: {url: "/tasks", dataType: "json"}
*
* If `findAll` is implemented with an object, it gets converted to
* a [can.Model.findAllData findAllData function]
* which is passed to [can.Model.makeFindAll makeFindAll] to create the external
* `findAll` method.
*
* @param {can.AjaxSettings} ajaxSettings A settings object that
* specifies the options available to pass to [can.ajax].
*
* @body
*
* ## Use
*
* `findAll( params, success(instances), error(xhr) ) -> Deferred` is used to retrieve model
* instances from the server. After implementing `findAll`, use it to retrieve instances of the model
* like:
*
* Recipe.findAll({favorite: true}, function(recipes){
* recipes[0].attr('name') //-> "Ice Water"
* }, function( xhr ){
* // called if an error
* }) //-> Deferred
*
*
* Before you can use `findAll`, you must implement it.
*
* ## Implement with a URL
*
* Implement findAll with a url like:
*
* Recipe = can.Model.extend({
* findAll : "/recipes.json"
* },{});
*
* The server should return data that looks like:
*
* [
* {"id" : 57, "name": "Ice Water"},
* {"id" : 58, "name": "Toast"}
* ]
*
* ## Implement with an Object
*
* Implement findAll with an object that specifies the parameters to
* `can.ajax` (jQuery.ajax) like:
*
* Recipe = can.Model.extend({
* findAll : {
* url: "/recipes.xml",
* dataType: "xml"
* }
* },{})
*
* ## Implement with a Function
*
* To implement with a function, `findAll` is passed __params__ to filter
* the instances retrieved from the server and it should return a
* deferred that resolves to an array of model data. For example:
*
* Recipe = can.Model.extend({
* findAll : function(params){
* return $.ajax({
* url: '/recipes.json',
* type: 'get',
* dataType: 'json'})
* }
* },{})
*
*/
findAll : {
url : "_shortName"
},
/**
* @description Retrieve a resource from a server.
* @function can.Model.findOne findOne
* @parent can.Model.static
*
* @signature `can.Model.findOne( params[, success[, error]] )`
*
* Retrieve a single instance from the server.
*
* @param {Object} params Values to filter the request or results with.
* @param {function(can.Model)} [success(model)] A callback to call on successful retrieval. The callback recieves
* the retrieved resource as a can.Model.
* @param {function(can.AjaxSettings)} [error(xhr)] A callback to call when an error occurs. The callback receives the
* XmlHttpRequest object.
* @return {can.Deferred} A deferred that resolves to a [can.Model.List] of retrieved models.
*
* @signature `can.Model.findOne: findOneData( params ) -> deferred`
*
* Implements `findOne` with a [can.Model.findOneData function]. This function
* is passed to [can.Model.makeFindOne makeFindOne] to create the external
* `findOne` method.
*
* findOne: function(params){
* return $.get("/task/"+params.id)
* }
*
* @param {can.Model.findOneData} findOneData A function that accepts parameters
* specifying an instance to retreive and returns a [can.Deferred]
* that resolves to that instance.
*
* @signature `can.Model.findOne: "[METHOD] /path/to/resource"`
*
* Implements `findOne` with a HTTP method and url to retrieve an instance's data.
*
* findOne: "GET /tasks/{id}"
*
* If `findOne` is implemented with a string, this gets converted to
* a [can.Model.makeFindOne makeFindOne function]
* which is passed to [can.Model.makeFindOne makeFindOne] to create the external
* `findOne` method.
*
* @param {HttpMethod} METHOD An HTTP method. Defaults to `"GET"`.
*
* @param {STRING} url The URL of the service to retrieve JSON data.
*
* @signature `can.Model.findOne: {ajaxSettings}`
*
* Implements `findOne` with a [can.AjaxSettings ajax settings object].
*
* findOne: {url: "/tasks/{id}", dataType: "json"}
*
* If `findOne` is implemented with an object, it gets converted to
* a [can.Model.makeFindOne makeFindOne function]
* which is passed to [can.Model.makeFindOne makeFindOne] to create the external
* `findOne` method.
*
* @param {can.AjaxSettings} ajaxSettings A settings object that
* specifies the options available to pass to [can.ajax].
*
* @body
*
* ## Use
*
* `findOne( params, success(instance), error(xhr) ) -> Deferred` is used to retrieve a model
* instance from the server.
*
* Use `findOne` like:
*
* Recipe.findOne({id: 57}, function(recipe){
* recipe.attr('name') //-> "Ice Water"
* }, function( xhr ){
* // called if an error
* }) //-> Deferred
*
* Before you can use `findOne`, you must implement it.
*
* ## Implement with a URL
*
* Implement findAll with a url like:
*
* Recipe = can.Model.extend({
* findOne : "/recipes/{id}.json"
* },{});
*
* If `findOne` is called like:
*
* Recipe.findOne({id: 57});
*
* The server should return data that looks like:
*
* {"id" : 57, "name": "Ice Water"}
*
* ## Implement with an Object
*
* Implement `findOne` with an object that specifies the parameters to
* `can.ajax` (jQuery.ajax) like:
*
* Recipe = can.Model.extend({
* findOne : {
* url: "/recipes/{id}.xml",
* dataType: "xml"
* }
* },{})
*
* ## Implement with a Function
*
* To implement with a function, `findOne` is passed __params__ to specify
* the instance retrieved from the server and it should return a
* deferred that resolves to the model data. Also notice that you now need to
* build the URL manually. For example:
*
* Recipe = can.Model.extend({
* findOne : function(params){
* return $.ajax({
* url: '/recipes/' + params.id,
* type: 'get',
* dataType: 'json'})
* }
* },{})
*
*
*/
findOne: {}
},
// Makes an ajax request `function` from a string.
// `ajaxMethod` - The `ajaxMethod` object defined above.
// `str` - The string the user provided. Ex: `findAll: "/recipes.json"`.
ajaxMaker = function(ajaxMethod, str){
// Return a `function` that serves as the ajax method.
return function(data){
// If the ajax method has it's own way of getting `data`, use that.
data = ajaxMethod.data ?
ajaxMethod.data.apply(this, arguments) :
// Otherwise use the data passed in.
data;
// Return the ajax method with `data` and the `type` provided.
return ajax(str || this[ajaxMethod.url || "_url"], data, ajaxMethod.type || "get")
}
}
can.Model = can.Observe({
fullName: "can.Model",
_reqs: 0,
/**
* @hide
* @function can.Model.setup
* @parent can.Model.static
*
* Configures
*
*/
setup : function(base){
// create store here if someone wants to use model without inheriting from it
this.store = {};
can.Observe.setup.apply(this, arguments);
// Set default list as model list
if(!can.Model){
return;
}
this.List = ML({Observe: this},{});
var self = this,
clean = can.proxy(this._clean, self);
// go through ajax methods and set them up
can.each(ajaxMethods, function(method, name){
// if an ajax method is not a function, it's either
// a string url like findAll: "/recipes" or an
// ajax options object like {url: "/recipes"}
if ( ! can.isFunction( self[name] )) {
// use ajaxMaker to convert that into a function
// that returns a deferred with the data
self[name] = ajaxMaker(method, self[name]);
}
// check if there's a make function like makeFindAll
// these take deferred function and can do special
// behavior with it (like look up data in a store)
if (self["make"+can.capitalize(name)]){
// pass the deferred method to the make method to get back
// the "findAll" method.
var newMethod = self["make"+can.capitalize(name)](self[name]);
can.Construct._overwrite(self, base, name,function(){
// increment the numer of requests
can.Model._reqs++;
var def = newMethod.apply(this, arguments);
var then = def.then(clean, clean);
then.abort = def.abort;
// attach abort to our then and return it
return then;
})
}
});
if(self.fullName == "can.Model" || !self.fullName){
self.fullName = "Model"+(++modelNum);
}
// Add ajax converters.
can.Model._reqs = 0;
this._url = this._shortName+"/{"+this.id+"}"
},
_ajax : ajaxMaker,
_makeRequest : makeRequest,
_clean : function(){
can.Model._reqs--;
if(!can.Model._reqs){
for(var id in this.store) {
if(!this.store[id]._bindings){
delete this.store[id];
}
}
}
return arguments[0];
},
/**
* @function can.Model.models models
* @parent can.Model.static
* @description Convert raw data into can.Model instances.
* @signature `can.Model.models(data[, oldList])`
* @param {Array<Object>} data The raw data from a `[can.Model.findAll findAll()]` request.
* @param {can.Model.List} [oldList] If supplied, this List will be updated with the data from
* __data__.
* @return {can.Model.List} A List of Models made from the raw data.
*
* @body
* `can.Model.models(data, xhr)` is used to
* convert the raw response of a [can.Model.findAll] request
* into a [can.Model.List] of model instances.
*
* This method is rarely called directly. Instead the deferred returned
* by findAll is piped into `models`. This creates a new deferred that
* resolves to a [can.Model.List] of instances instead of an array of
* simple JS objects.
*
* If your server is returning data in non-standard way,
* overwriting `can.Model.models` is the best way to normalize it.
*
* ## Quick Example
*
* The following uses models to convert to a [can.Model.List] of model
* instances.
*
* Task = can.Model.extend()
* var tasks = Task.models([
* {id: 1, name : "dishes", complete : false},
* {id: 2, name: "laundry", compelte: true}
* ])
*
* tasks.attr("0.complete", true)
*
* ## Non-standard Services
*
* `can.Model.models` expects data to be an array of name-value pair
* objects like:
*
* [{id: 1, name : "dishes"},{id:2, name: "laundry"}, ...]
*
* It can also take an object with additional data about the array like:
*
* {
* count: 15000 //how many total items there might be
* data: [{id: 1, name : "justin"},{id:2, name: "brian"}, ...]
* }
*
* In this case, models will return a [can.Model.List] of instances found in
* data, but with additional properties as expandos on the list:
*
* var tasks = Task.models({
* count : 1500,
* data : [{id: 1, name: 'dishes'}, ...]
* })
* tasks.attr("name") // -> 'dishes'
* tasks.count // -> 1500
*
* ### Overwriting Models
*
* If your service returns data like:
*
* {thingsToDo: [{name: "dishes", id: 5}]}
*
* You will want to overwrite models to pass the base models what it expects like:
*
* Task = can.Model.extend({
* models : function(data){
* return can.Model.models.call(this,data.thingsToDo);
* }
* },{})
*
* `can.Model.models` passes each intstance's data to `can.Model.model` to
* create the individual instances.
*/
models: function( instancesRawData, oldList ) {
// until "end of turn", increment reqs counter so instances will be added to the store
can.Model._reqs++;
if ( ! instancesRawData ) {
return;
}
if ( instancesRawData instanceof this.List ) {
return instancesRawData;
}
// Get the list type.
var self = this,
tmp = [],
res = oldList instanceof can.Observe.List ? oldList : new( self.List || ML),
// Did we get an `array`?
arr = can.isArray(instancesRawData),
// Did we get a model list?
ml = (instancesRawData instanceof ML),
// Get the raw `array` of objects.
raw = arr ?
// If an `array`, return the `array`.
instancesRawData :
// Otherwise if a model list.
(ml ?
// Get the raw objects from the list.
instancesRawData.serialize() :
// Get the object's data.
instancesRawData.data),
i = 0;
if(typeof raw === 'undefined') {
throw new Error('Could not get any raw data while converting using .models');
}
//!steal-remove-start
if ( ! raw.length ) {
steal.dev.warn("model.js models has no data.")
}
//!steal-remove-end
if(res.length) {
res.splice(0);
}
can.each(raw, function( rawPart ) {
tmp.push( self.model( rawPart ));
});
// We only want one change event so push everything at once
res.push.apply(res, tmp);
if ( ! arr ) { // Push other stuff onto `array`.
can.each(instancesRawData, function(val, prop){
if ( prop !== 'data' ) {
res.attr(prop, val);
}
})
}
// at "end of turn", clean up the store
setTimeout(can.proxy(this._clean, this), 1);
return res;
},
/**
* @function can.Model.model model
* @parent can.Model.static
* @description Convert raw data into a can.Model instance.
* @signature `can.Model.model(data)`
* @param {Object} data The data to convert to a can.Model instance.
* @return {can.Model} An instance of can.Model made with the given data.
*
* @body
* `can.Model.model(attributes)` is used to convert data from the server into
* a model instance. It is rarely called directly. Instead it is invoked as
* a result of [can.Model.findOne] or [can.Model.findAll].
*
* If your server is returning data in non-standard way,
* overwriting `can.Model.model` is a good way to normalize it.
*
* ## Example
*
* The following uses `model` to convert to a model
* instance.
*
* Task = can.Model.extend({},{})
* var task = Task.model({id: 1, name : "dishes", complete : false})
*
* tasks.attr("complete", true)
*
* `Task.model(attrs)` is very similar to simply calling `new Model(attrs)` except
* that it checks the model's store if the instance has already been created. The model's
* store is a collection of instances that have event handlers.
*