-
Notifications
You must be signed in to change notification settings - Fork 373
/
Copy pathmodel.js
1825 lines (1761 loc) · 55.2 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
/*global OpenAjax: true */
steal('jquery/class', 'jquery/lang/string', function() {
// Common helper methods taken from jQuery (or other places)
// Keep here so someday can be abstracted
var $String = $.String,
getObject = $String.getObject,
underscore = $String.underscore,
classize = $String.classize,
isArray = $.isArray,
makeArray = $.makeArray,
extend = $.extend,
each = $.each,
trigger = function(obj, event, args){
$.event.trigger(event, args, obj, true)
},
// used to make an ajax request where
// ajaxOb - a bunch of options
// data - the attributes or data that will be sent
// success - callback function
// error - error callback
// fixture - the name of the fixture (typically a path or something on $.fixture
// type - the HTTP request type (defaults to "post")
// dataType - how the data should return (defaults to "json")
ajax = function(ajaxOb, data, success, error, fixture, type, dataType ) {
// if we get a string, handle it
if ( typeof ajaxOb == "string" ) {
// if there's a space, it's probably the type
var sp = ajaxOb.indexOf(" ")
if ( sp > -1 ) {
ajaxOb = {
url: ajaxOb.substr(sp + 1),
type: ajaxOb.substr(0, sp)
}
} else {
ajaxOb = {url : ajaxOb}
}
}
// if we are a non-array object, copy to a new attrs
ajaxOb.data = typeof data == "object" && !isArray(data) ?
extend(ajaxOb.data || {}, data) : data;
// get the url with any templated values filled out
ajaxOb.url = $String.sub(ajaxOb.url, ajaxOb.data, true);
return $.ajax(extend({
type: type || "post",
dataType: dataType ||"json",
fixture: fixture,
success : success,
error: error
},ajaxOb));
},
// guesses at a fixture name where
// extra - where to look for 'MODELNAME'+extra fixtures (ex: "Create" -> '-recipeCreate')
// or - if the first fixture fails, default to this
fixture = function( model, extra, or ) {
// get the underscored shortName of this Model
var u = underscore(model.shortName),
// the first place to look for fixtures
f = "-" + u + (extra || "");
// if the fixture exists in $.fixture
return $.fixture && $.fixture[f] ?
// return the name
f :
// or return or
or ||
// or return a fixture derived from the path
"//" + underscore(model.fullName).replace(/\.models\..*/, "").replace(/\./g, "/") + "/fixtures/" + u + (extra || "") + ".json";
},
// takes attrs, and adds it to the attrs (so it can be added to the url)
// if attrs already has an id, it means it's trying to update the id
// in this case, it sets the new ID as newId.
addId = function( model, attrs, id ) {
attrs = attrs || {};
var identity = model.id;
if ( attrs[identity] && attrs[identity] !== id ) {
attrs["new" + $String.capitalize(id)] = attrs[identity];
delete attrs[identity];
}
attrs[identity] = id;
return attrs;
},
// returns the best list-like object (list is passed)
getList = function( type ) {
var listType = type || $.Model.List || Array;
return new listType();
},
// a helper function for getting an id from an instance
getId = function( inst ) {
return inst[inst.constructor.id]
},
// returns a collection of unique items
// this works on objects by adding a "__u Nique" property.
unique = function( items ) {
var collect = [];
// check unique property, if it isn't there, add to collect
each(items, function( i, item ) {
if (!item["__u Nique"] ) {
collect.push(item);
item["__u Nique"] = 1;
}
});
// remove unique
return each(collect, function( i, item ) {
delete item["__u Nique"];
});
},
// helper makes a request to a static ajax method
// it also calls updated, created, or destroyed
// and it returns a deferred that resolvesWith self and the data
// returned from the ajax request
makeRequest = function( self, type, success, error, method ) {
// create the deferred makeRequest will return
var deferred = $.Deferred(),
// on a successful ajax request, call the
// updated | created | destroyed method
// then resolve the deferred
resolve = function( data ) {
self[method || type + "d"](data);
deferred.resolveWith(self, [self, data, type]);
},
// on reject reject the deferred
reject = function( data ) {
deferred.rejectWith(self, [data])
},
// the args to pass to the ajax method
args = [self.serialize(), resolve, reject],
// the Model
model = self.constructor,
jqXHR,
promise = deferred.promise();
// destroy does not need data
if ( type == 'destroy' ) {
args.shift();
}
// update and destroy need the id
if ( type !== 'create' ) {
args.unshift(getId(self))
}
// hook up success and error
deferred.then(success);
deferred.fail(error);
// call the model's function and hook up
// abort
jqXHR = model[type].apply(model, args);
if(jqXHR && jqXHR.abort){
promise.abort = function(){
jqXHR.abort();
}
}
return promise;
},
// a quick way to tell if it's an object and not some string
isObject = function( obj ) {
return typeof obj === 'object' && obj !== null && obj;
},
$method = function( name ) {
return function( eventType, handler ) {
return $.fn[name].apply($([this]), arguments);
}
},
bind = $method('bind'),
unbind = $method('unbind'),
STR_CONSTRUCTOR = 'constructor';
/**
* @class jQuery.Model
* @parent jquerymx
* @download http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/model/model.js
* @test jquery/model/qunit.html
* @plugin jquery/model
* @description Models and apps data layer.
*
* Models super-charge an application's
* data layer, making it easy to:
*
* - Get and modify data from the server
* - Listen to changes in data
* - Setting and retrieving models on elements
* - Deal with lists of data
* - Do other good stuff
*
* Model inherits from [jQuery.Class $.Class] and make use
* of REST services and [http://api.jquery.com/category/deferred-object/ deferreds]
* so these concepts are worth exploring. Also,
* the [mvc.model Get Started with jQueryMX] has a good walkthrough of $.Model.
*
*
* ## Get and modify data from the server
*
* $.Model makes connecting to a JSON REST service
* really easy. The following models <code>todos</code> by
* describing the services that can create, retrieve,
* update, and delete todos.
*
* $.Model('Todo',{
* findAll: 'GET /todos.json',
* findOne: 'GET /todos/{id}.json',
* create: 'POST /todos.json',
* update: 'PUT /todos/{id}.json',
* destroy: 'DELETE /todos/{id}.json'
* },{});
*
* This lets you create, retrieve, update, and delete
* todos programatically:
*
* __Create__
*
* Create a todo instance and
* call <code>[$.Model::save save]\(success, error\)</code>
* to create the todo on the server.
*
* // create a todo instance
* var todo = new Todo({name: "do the dishes"})
*
* // save it on the server
* todo.save();
*
* __Retrieve__
*
* Retrieve a list of todos from the server with
* <code>[$.Model.findAll findAll]\(params, callback(items)\)</code>:
*
* Todo.findAll({}, function( todos ){
*
* // print out the todo names
* $.each(todos, function(i, todo){
* console.log( todo.name );
* });
* });
*
* Retrieve a single todo from the server with
* <code>[$.Model.findOne findOne]\(params, callback(item)\)</code>:
*
* Todo.findOne({id: 5}, function( todo ){
*
* // print out the todo name
* console.log( todo.name );
* });
*
* __Update__
*
* Once an item has been created on the server,
* you can change its properties and call
* <code>save</code> to update it on the server.
*
* // update the todos' name
* todo.attr('name','Take out the trash')
*
* // update it on the server
* todo.save()
*
*
* __Destroy__
*
* Call <code>[$.Model.prototype.destroy destroy]\(success, error\)</code>
* to delete an item on the server.
*
* todo.destroy()
*
* ## Listen to changes in data
*
* Listening to changes in data is a critical part of
* the [http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller Model-View-Controller]
* architecture. $.Model lets you listen to when an item is created, updated, destroyed
* or its properties are changed. Use
* <code>Model.[$.Model.bind bind]\(eventType, handler(event, model)\)</code>
* to listen to all events of type on a model and
* <code>model.[$.Model.prototype.bind bind]\(eventType, handler(event)\)</code>
* to listen to events on a specific instance.
*
* __Create__
*
* // listen for when any todo is created
* Todo.bind('created', function( ev, todo ) {...})
*
* // listen for when a specific todo is created
* var todo = new Todo({name: 'do dishes'})
* todo.bind('created', function( ev ) {...})
*
* __Update__
*
* // listen for when any todo is updated
* Todo.bind('updated', function( ev, todo ) {...})
*
* // listen for when a specific todo is created
* Todo.findOne({id: 6}, function( todo ) {
* todo.bind('updated', function( ev ) {...})
* })
*
* __Destroy__
*
* // listen for when any todo is destroyed
* Todo.bind('destroyed', function( ev, todo ) {...})
*
* // listen for when a specific todo is destroyed
* todo.bind('destroyed', function( ev ) {...})
*
* __Property Changes__
*
* // listen for when the name property changes
* todo.bind('name', function(ev){ })
*
* __Listening with Controller__
*
* You should be using controller to listen to model changes like:
*
* $.Controller('Todos',{
* "{Todo} updated" : function(Todo, ev, todo) {...}
* })
*
*
* ## Setting and retrieving data on elements
*
* Almost always, we use HTMLElements to represent
* data to the user. When that data changes, we update those
* elements to reflect the new data.
*
* $.Model has helper methods that make this easy. They
* let you "add" a model to an element and also find
* all elements that have had a model "added" to them.
*
* Consider a todo list widget
* that lists each todo in the page and when a todo is
* deleted, removes it.
*
* <code>[jQuery.fn.model $.fn.model]\(item\)</code> lets you set or read a model
* instance from an element:
*
* Todo.findAll({}, function( todos ) {
*
* $.each(todos, function(todo) {
* $('<li>').model(todo)
* .text(todo.name)
* .appendTo('#todos')
* });
* });
*
* When a todo is deleted, get its element with
* <code>item.[$.Model.prototype.elements elements]\(context\)</code>
* and remove it from the page.
*
* Todo.bind('destroyed', function( ev, todo ) {
* todo.elements( $('#todos') ).remove()
* })
*
* __Using EJS and $.Controller__
*
* [jQuery.View $.View] and [jQuery.EJS EJS] makes adding model data
* to elements easy. We can implement the todos widget like the following:
*
* $.Controller('Todos',{
* init: function(){
* this.element.html('//todos/views/todos.ejs', Todo.findAll({}) );
* },
* "{Todo} destroyed": function(Todo, ev, todo) {
* todo.elements( this.element ).remove()
* }
* })
*
* In todos.ejs
*
* @codestart html
* <% for(var i =0; i < todos.length; i++){ %>
* <li <%= todos[i] %>><%= todos[i].name %></li>
* <% } %>
* @codeend
*
* Notice how you can add a model to an element with <code><%= model %></code>
*
* ## Lists
*
* [$.Model.List $.Model.List] lets you handle multiple model instances
* with ease. A List acts just like an <code>Array</code>, but you can add special properties
* to it and listen to events on it.
*
* <code>$.Model.List</code> has become its own plugin, read about it
* [$.Model.List here].
*
* ## Other Good Stuff
*
* Model can make a lot of other common tasks much easier.
*
* ### Type Conversion
*
* Data from the server often needs massaging to make it more useful
* for JavaScript. A typical example is date data which is
* commonly passed as
* a number representing the Julian date like:
*
* { name: 'take out trash',
* id: 1,
* dueDate: 1303173531164 }
*
* But instead, you want a JavaScript date object:
*
* date.attr('dueDate') //-> new Date(1303173531164)
*
* By defining property-type pairs in [$.Model.attributes attributes],
* you can have model auto-convert values from the server into more useful types:
*
* $.Model('Todo',{
* attributes : {
* dueDate: 'date'
* }
* },{})
*
* ### Associations
*
* The [$.Model.attributes attributes] property also
* supports associations. For example, todo data might come back with
* User data as an owner property like:
*
* { name: 'take out trash',
* id: 1,
* owner: { name: 'Justin', id: 3} }
*
* To convert owner into a User model, set the owner type as the User's
* [$.Model.model model]<code>( data )</code> method:
*
* $.Model('Todo',{
* attributes : {
* owner: 'User.model'
* }
* },{})
*
* ### Helper Functions
*
* Often, you need to perform repeated calculations
* with a model's data. You can create methods in the model's
* prototype and they will be available on
* all model instances.
*
* The following creates a <code>timeRemaining</code> method that
* returns the number of seconds left to complete the todo:
*
* $.Model('Todo',{
* },{
* timeRemaining : function(){
* return new Date() - new Date(this.dueDate)
* }
* })
*
* // create a todo
* var todo = new Todo({dueDate: new Date()});
*
* // show off timeRemaining
* todo.timeRemaining() //-> Number
*
* ### Deferreds
*
* Model methods that make requests to the server such as:
* [$.Model.findAll findAll], [$.Model.findOne findOne],
* [$.Model.prototype.save save], and [$.Model.prototype.destroy destroy] return a
* [jquery.model.deferreds deferred] that resolves to the item(s)
* being retrieved or modified.
*
* Deferreds can make a lot of asynchronous code much easier. For example, the following
* waits for all users and tasks before continuing :
*
* $.when(Task.findAll(), User.findAll())
* .then(function( tasksRes, usersRes ){ ... })
*
* ### Validations
*
* [jquery.model.validations Validate] your model's attributes.
*
* $.Model("Contact",{
* init : function(){
* this.validate("birthday",function(){
* if(this.birthday > new Date){
* return "your birthday needs to be in the past"
* }
* })
* }
* ,{});
*
*
*/
// methods that we'll weave into model if provided
ajaxMethods =
/**
* @Static
*/
{
create: function( str ) {
/**
* @function create
* Create is used by [$.Model.prototype.save save] to create a model instance on the server.
*
* The easiest way to implement create is to give it the url to post data to:
*
* $.Model("Recipe",{
* create: "/recipes"
* },{})
*
* This lets you create a recipe like:
*
* new Recipe({name: "hot dog"}).save();
*
* You can also implement create by yourself. Create gets called with:
*
* - `attrs` - the [$.Model.serialize serialized] model attributes.
* - `success(newAttrs)` - a success handler.
* - `error` - an error handler.
*
* You just need to call success back with
* an object 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:
*
* $.Model("Recipe", {
* create : function(attrs, success, error){
* $.post("/recipes.json",attrs, success,"json");
* }
* },{})
*
*
* @param {Object} attrs Attributes on the model instance
* @param {Function} success(newAttrs) the callback function, it must be called with an object
* that has the id of the new instance and any other attributes the service needs to add.
* @param {Function} error a function to callback if something goes wrong.
*/
return function( attrs, success, error ) {
return ajax(str || this._shortName, attrs, success, error, fixture(this, "Create", "-restCreate"))
};
},
update: function( str ) {
/**
* @function update
* Update is used by [$.Model.prototype.save save] to
* update a model instance on the server.
*
* The easist way to implement update is to just give it the url to `PUT` data to:
*
* $.Model("Recipe",{
* update: "/recipes/{id}"
* },{})
*
* This lets you update a recipe like:
*
* // PUT /recipes/5 {name: "Hot Dog"}
* Recipe.update(5, {name: "Hot Dog"},
* function(){
* this.name //this is the updated recipe
* })
*
* If your server doesn't use PUT, you can change it to post like:
*
* $.Model("Recipe",{
* update: "POST /recipes/{id}"
* },{})
*
* Your 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"
* }
*
* You can also implement create by yourself. You just need to call success back with
* 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:
*
* $.Model("Recipe", {
* update : function(id, attrs, success, error){
* $.post("/recipes/"+id+".json",attrs, success,"json");
* }
* },{})
*
*
* @param {String} id the id of the model instance
* @param {Object} attrs Attributes on the model instance
* @param {Function} success(attrs) the callback function. It optionally accepts
* an object of attribute / value pairs of property changes the client doesn't already
* know about. For example, when you update a name property, the server might
* update other properties as well (such as updatedAt). The server should send
* these properties as the response to updates. Passing them to success will
* update the model instance with these properties.
*
* @param {Function} error a function to callback if something goes wrong.
*/
return function( id, attrs, success, error ) {
return ajax( str || this._shortName+"/{"+this.id+"}", addId(this, attrs, id), success, error, fixture(this, "Update", "-restUpdate"), "put")
}
},
destroy: function( str ) {
/**
* @function destroy
* Destroy is used to remove a model instance from the server.
*
* You can implement destroy with a string like:
*
* $.Model("Thing",{
* destroy : "POST /thing/destroy/{id}"
* })
*
* Or you can implement destroy manually like:
*
* $.Model("Thing",{
* destroy : function(id, success, error){
* $.post("/thing/destroy/"+id,{}, success);
* }
* })
*
* You just have to call success if the destroy was successful.
*
* @param {String|Number} id the id of the instance you want destroyed
* @param {Function} success the callback function, it must be called with an object
* that has the id of the new instance and any other attributes the service needs to add.
* @param {Function} error a function to callback if something goes wrong.
*/
return function( id, success, error ) {
var attrs = {};
attrs[this.id] = id;
return ajax( str || this._shortName+"/{"+this.id+"}", attrs, success, error, fixture(this, "Destroy", "-restDestroy"), "delete")
}
},
findAll: function( str ) {
/**
* @function findAll
* FindAll is used to retrive a model instances from the server.
* findAll returns a deferred ($.Deferred).
*
* You can implement findAll with a string:
*
* $.Model("Thing",{
* findAll : "/things.json"
* },{})
*
* Or you can implement it yourself. The `dataType` attribute
* is used to convert a JSON array of attributes
* to an array of instances. It calls <code>[$.Model.models]\(raw\)</code>. For example:
*
* $.Model("Thing",{
* findAll : function(params, success, error){
* return $.ajax({
* url: '/things.json',
* type: 'get',
* dataType: 'json thing.models',
* data: params,
* success: success,
* error: error})
* }
* },{})
*
*
* @param {Object} params data to refine the results. An example might be passing {limit : 20} to
* limit the number of items retrieved.
* @param {Function} success(items) called with an array (or Model.List) of model instances.
* @param {Function} error
*/
return function( params, success, error ) {
return ajax( str || this._shortName, params, success, error, fixture(this, "s"), "get", "json " + this._shortName + ".models");
};
},
findOne: function( str ) {
/**
* @function findOne
* FindOne is used to retrive a model instances from the server. By implementing
* findOne along with the rest of the [jquery.model.services service api], your models provide an abstract
* service API.
*
* You can implement findOne with a string:
*
* $.Model("Thing",{
* findOne : "/things/{id}.json"
* },{})
*
* Or you can implement it yourself.
*
* $.Model("Thing",{
* findOne : function(params, success, error){
* var self = this,
* id = params.id;
* delete params.id;
* return $.get("/things/"+id+".json",
* params,
* success,
* "json thing.model")
* }
* },{})
*
*
* @param {Object} params data to refine the results. This is often something like {id: 5}.
* @param {Function} success(item) called with a model instance
* @param {Function} error
*/
return function( params, success, error ) {
return ajax(str || this._shortName+"/{"+this.id+"}", params, success, error, fixture(this), "get", "json " + this._shortName + ".model");
};
}
};
jQuery.Class("jQuery.Model", {
setup: function( superClass, stat, proto ) {
var self = this,
fullName = this.fullName;
//we do not inherit attributes (or validations)
each(["attributes", "validations"], function( i, name ) {
if (!self[name] || superClass[name] === self[name] ) {
self[name] = {};
}
})
//add missing converters and serializes
each(["convert", "serialize"], function( i, name ) {
if ( superClass[name] != self[name] ) {
self[name] = extend({}, superClass[name], self[name]);
}
});
this._fullName = underscore(fullName.replace(/\./g, "_"));
this._shortName = underscore(this.shortName);
if ( fullName.indexOf("jQuery") == 0 ) {
return;
}
//add this to the collection of models
//$.Model.models[this._fullName] = this;
if ( this.listType ) {
this.list = new this.listType([]);
}
//!steal-remove-start
if (!proto ) {
steal.dev.warn("model.js " + fullName + " has no static properties. You probably need ,{} ")
}
//!steal-remove-end
each(ajaxMethods, function(name, method){
var prop = self[name];
if ( typeof prop !== 'function' ) {
self[name] = method(prop);
}
});
//add ajax converters
var converters = {},
convertName = "* " + this._shortName + ".model";
converters[convertName + "s"] = this.proxy('models');
converters[convertName] = this.proxy('model');
$.ajaxSetup({
converters: converters
});
},
/**
* @attribute attributes
* Attributes contains a map of attribute names/types.
* You can use this in conjunction with
* [$.Model.convert] to provide automatic
* [jquery.model.typeconversion type conversion] (including
* associations).
*
* The following converts dueDates to JavaScript dates:
*
*
* $.Model("Contact",{
* attributes : {
* birthday : 'date'
* },
* convert : {
* date : function(raw){
* if(typeof raw == 'string'){
* var matches = raw.match(/(\d+)-(\d+)-(\d+)/)
* return new Date( matches[1],
* (+matches[2])-1,
* matches[3] )
* }else if(raw instanceof Date){
* return raw;
* }
* }
* }
* },{})
*
* ## Associations
*
* Attribute type values can also represent the name of a
* function. The most common case this is used is for
* associated data.
*
* For example, a Deliverable might have many tasks and
* an owner (which is a Person). The attributes property might
* look like:
*
* attributes : {
* tasks : "App.Models.Task.models"
* owner: "App.Models.Person.model"
* }
*
* This points tasks and owner properties to use
* <code>Task.models</code> and <code>Person.model</code>
* to convert the raw data into an array of Tasks and a Person.
*
* Note that the full names of the models themselves are <code>App.Models.Task</code>
* and <code>App.Models.Person</code>. The _.model_ and _.models_ parts are appended
* for the benefit of [$.Model.convert convert] to identify the types as
* models.
*
* @demo jquery/model/pages/associations.html
*
*/
attributes: {},
/**
* $.Model.model is used as a [http://api.jquery.com/extending-ajax/#Converters Ajax converter]
* to convert the response of a [$.Model.findOne] request
* into a model instance.
*
* You will never call this method directly. Instead, you tell $.ajax about it in findOne:
*
* $.Model('Recipe',{
* findOne : function(params, success, error ){
* return $.ajax({
* url: '/services/recipes/'+params.id+'.json',
* type: 'get',
*
* dataType : 'json recipe.model' //LOOK HERE!
* });
* }
* },{})
*
* This makes the result of findOne a [http://api.jquery.com/category/deferred-object/ $.Deferred]
* that resolves to a model instance:
*
* var deferredRecipe = Recipe.findOne({id: 6});
*
* deferredRecipe.then(function(recipe){
* console.log('I am '+recipes.description+'.');
* })
*
* ## Non-standard Services
*
* $.jQuery.model expects data to be name-value pairs like:
*
* {id: 1, name : "justin"}
*
* It can also take an object with attributes in a data, attributes, or
* 'shortName' property. For a App.Models.Person model the following will all work:
*
* { data : {id: 1, name : "justin"} }
*
* { attributes : {id: 1, name : "justin"} }
*
* { person : {id: 1, name : "justin"} }
*
*
* ### Overwriting Model
*
* If your service returns data like:
*
* {id : 1, name: "justin", data: {foo : "bar"} }
*
* This will confuse $.Model.model. You will want to overwrite it to create
* an instance manually:
*
* $.Model('Person',{
* model : function(data){
* return new this(data);
* }
* },{})
*
*
* @param {Object} attributes An object of name-value pairs or an object that has a
* data, attributes, or 'shortName' property that maps to an object of name-value pairs.
* @return {Model} an instance of the model
*/
model: function( attributes ) {
if (!attributes ) {
return null;
}
if ( attributes instanceof this ) {
attributes = attributes.serialize();
}
return new this(
// checks for properties in an object (like rails 2.0 gives);
isObject(attributes[this._shortName]) || isObject(attributes.data) || isObject(attributes.attributes) || attributes);
},
/**
* $.Model.models is used as a [http://api.jquery.com/extending-ajax/#Converters Ajax converter]
* to convert the response of a [$.Model.findAll] request
* into an array (or [$.Model.List $.Model.List]) of model instances.
*
* You will never call this method directly. Instead, you tell $.ajax about it in findAll:
*
* $.Model('Recipe',{
* findAll : function(params, success, error ){
* return $.ajax({
* url: '/services/recipes.json',
* type: 'get',
* data: params
*
* dataType : 'json recipe.models' //LOOK HERE!
* });
* }
* },{})
*
* This makes the result of findAll a [http://api.jquery.com/category/deferred-object/ $.Deferred]
* that resolves to a list of model instances:
*
* var deferredRecipes = Recipe.findAll({});
*
* deferredRecipes.then(function(recipes){
* console.log('I have '+recipes.length+'recipes.');
* })
*
* ## Non-standard Services
*
* $.jQuery.models expects data to be an array of name-value pairs like:
*
* [{id: 1, name : "justin"},{id:2, name: "brian"}, ...]
*
* 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 an array of instances found in
* data, but with additional properties as expandos on the array:
*
* var people = Person.models({
* count : 1500,
* data : [{id: 1, name: 'justin'}, ...]
* })
* people[0].name // -> justin
* people.count // -> 1500
*
* ### Overwriting Models
*
* If your service returns data like:
*
* {ballers: [{name: "justin", id: 5}]}
*
* You will want to overwrite models to pass the base models what it expects like:
*
* $.Model('Person',{
* models : function(data){
* return this._super(data.ballers);
* }
* },{})
*
* @param {Array} instancesRawData an array of raw name - value pairs.
* @return {Array} a JavaScript array of instances or a [$.Model.List list] of instances
* if the model list plugin has been included.
*/
models: function( instancesRawData ) {
if (!instancesRawData ) {
return null;
}
// get the list type
var res = getList(this.List),
// did we get an array
arr = isArray(instancesRawData),
// cache model list
ML = $.Model.List,
// did we get a model list?
ml = (ML && instancesRawData instanceof ML),
// get the raw array of objects
raw = arr ?