forked from cordjs/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollection.coffee
1590 lines (1318 loc) · 56.8 KB
/
Collection.coffee
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
define [
'cord!isBrowser'
'cord!Module'
'cord!utils/Defer'
'cord!utils/Future'
'monologue' + (if CORD_IS_BROWSER then '' else '.js')
'underscore'
], (isBrowser, Module, Defer, Future, Monologue, _) ->
class ModelNotExists extends Error
constructor: (@message) ->
@name = 'ModelNotExists'
class Collection extends Module
@include Monologue.prototype
@__name: 'Collection' # obfuscation support
_filterType: ':none' # :none | :local | :backend
_filterId: null
_filterParams: null # params for filter
_filterFunction: null
_defaultRefreshPages: 3 #default amount of pages to refresh
_orderBy: null
_fields: null
# correctly ordered list of models of the collection
_models: null
# cached total (not only loaded) count of models in this collection
_totalCount: null
_cacheLoaded: false
_totalCountFromCache: false
# index of models by id
_byId: null
_initialized: false
# partially loaded collection properties
_loadedStart: 4294967295
_loadedEnd: -1
_hasLimits: null
_requestParams: null
_queryQueue: null
# helper value for event propagation optimization
_selfEmittedChangeModelId: null
# custom rest access point
_accessPoint: null
#Last time collection was queried from backend
_lastQueryTime: 0
# Tags for collection refreshing and other activities. Used for background refreshing of collections
# Tags events are propagated trough appropriate ModelRepo
# Tag is a user-defined string, collection reaction on tags defined by parameter 'tagsActions'
# all tag actions are executed within collection context
# There are predefined tags actions:
# 'refresh' - immediate refresh loaded parts of the collection
# 'liveUpdate' - immediate refresh if collection is alive (has any 'change' subscriptons)
# 'clearCache' - clears cache and timeouts
# Example:
# tags:
# 'project.10000': 'liveUpdate'
# 'any': 'liveUpdate'
_tags: null
# default tag action and proirity for user-defined tags
@_defaultTagAction: 'tagLiveUpdate'
@_defaultTagPriority: 100
# handles tags broadcast
# params is an object with array of tags and mods (modificators) which wisll be passed as param into tagAction
# params =
# 'project.1000002':
# ifContain: 1000003
_handleTagBroadcast: (params) ->
# Search for mathing tags anf actions
return if not _.isArray(@_sortedTags)
for tagObject in @_sortedTags
tag = tagObject.tag
tagValue = tagObject.value
if params[tag] != undefined
if _.isFunction(tagValue.action)
if tagValue.action.call(this, params[tag])
break
else
if @[tagValue.action].call(this, params[tag])
break
tagsRefresh: (mods) ->
startPage = @_loadedStart / @_pageSize + 1
@partialRefresh(startPage, @_defaultRefreshPages, 0, true)
true
tagLiveUpdate: (mods) ->
@_lastQueryTime = 0
if @hasActiveSubscriptions()
startPage = if @_pageSize > 0 then @_loadedStart / @_pageSize + 1 else 1
@partialRefresh(startPage, @_defaultRefreshPages)
true
else
false
tagClearCache: (mods) ->
# Clear last query time, which means the collection could be updated
@_lastQueryTime = 0
if not @hasActiveSubscriptions()
@euthanize()
true
else
false
tagRefreshIfExists: (model) ->
# Uptade the collection if it already contains the model and has any active 'change' subscriptions
id = parseInt(if _.isObject(model) then model.id else model)
if id and not isNaN(id) and @_byId[id] and @hasActiveSubscriptions()
@refresh(id)
true
else
false
hasField: (fieldName) ->
###
Detect if collection requests the particular field of part of it
###
for fieldName in @_fields
return true if fieldName.indexOf(fieldName) == 0
false
@generateName: (options) ->
###
Generates and returns unique "checksum" name of a collection depending only of the given options.
This allows to reuse collections with the totally same options instead of duplicating them.
@param Object options same options, that will be passed to the collection constructor
@return String
###
accessPoint = options.accessPoint ? ''
orderBy = options.orderBy ? ''
filterId = options.filterId ? ''
filterParams = options.filterParams ? ''
filterParams = filterParams.join(',') if _.isArray(filterParams)
filter = _.reduce options.filter , (memo, value, index) ->
memo + index + '_' + value
, ''
if options.requestParams
requestOptions = _.reduce options.requestParams, (memo, value, index) ->
memo + index + '_' + value
, ''
else
requestOptions = '';
clazz = if options.collectionClass? then options.collectionClass.__name else ''
fields = options.fields ? []
calc = options.calc ? []
id = options.id ? 0
pageSize = if options.pageSize then options.pageSize else ''
collectionVersion = global.config.static.collection
tagz = if options.tags then _.keys(options.tags).sort().join('_') else ''
[
collectionVersion
clazz
accessPoint
fields.sort().join(',')
calc.sort().join(',')
filterId
filterParams
filter
orderBy
id
requestOptions
pageSize
tagz
].join('|').replace(/\:/g, '')
constructor: (@repo, @name, options) ->
###
@param ModelRepo repo model repository to which the collection belongs
@param String name unique name of the collection in the model repository
@param Object options collection filtering, ordering and field fetching options
###
@_models = []
@_byId = {}
@_filterType = options.filterType ? ':backend'
@_fields = options.fields ? []
@_reconnect = options.reconnect ? false
if options.model
@_fillModelList [options.model]
@_orderBy = options.orderBy ? null
@_filterId = null
@_filterParams = null
@_id = parseInt(options.model.id)
@_filter = {}
else
@_orderBy = options.orderBy ? null
@_filterId = options.filterId ? null
@_filterParams = options.filterParams ? null
@_id = options.id ? 0
@_filter = options.filter ? {}
@_pageSize = options.pageSize ? 0
@_fillModelList(options.models, options.start, options.end) if _.isArray(options.models)
#special case - fixed collections, when model are already provided and we have no need to do anything with them
if options.fixed && options.models
@_fixed = true
@_byId = options.models
@_models = _.values options.models
@_requestParams = options.requestParams ? {}
@_tags = {}
@_queryQueue =
loadingStart: @_loadedStart
loadingEnd: @_loadedEnd
list: []
@_accessPoint = options.accessPoint ? null
# subscribe for model changes to smart-proxy them to the collections model instances
@_changeSubscription = @repo.on('change', @_handleModelChange).withContext(this)
@_tagsSubscription = @repo.on('tags', @_handleTagBroadcast).withContext(this)
injectTags: (tags) ->
###
inject tags into the collections
###
# Parser and initialize tags
# tags could be set in 3 forms:
# - a string of tags divided by coma: 'project.100002, project.1000003'
# - an array of tags: ['project.1000002', 'project.100003']
# - an object like:
# 'project.1000003':
# action: (mods) -> ...
# proiroty: 100
@_tags = {}
if tags
if _.isObject(tags)
for key, value of tags
@_tags[key] =
action: if value.action then value.action else Collection._defaultTagAction
priority: if not isNaN(Number(value.priority)) then Number(value.priority) else Collection._defaultTagPriority
else if _.isArray(tags) or _.isString(tags)
rawTags =
if _.isString(tags)
_.filter tags.split(','), item -> item.trim()
else
tags
for value in rawTags
@_tags[value] =
action: Collection._defaultTagAction
priority: Collection._defaultTagPriority
else
throw new Error('Unknown \'tags\' option: ' + options.tag)
if not @_tags['id.any']
@_tags['id.any'] =
action: 'tagRefreshIfExists'
priority: Number.POSITIVE_INFINITY # if no other tags occured
arrayOfTags = []
for key, value of @_tags
arrayOfTags.push
tag: key
value: value
@_sortedTags = _.sortBy arrayOfTags, (tagObject) -> tagObject.value.priority
euthanize: ->
###
Remove collection from Repo and cache
###
@_changeSubscription.unsubscribe() if @_changeSubscription
@_tagsSubscription.unsubscribe() if @_tagsSubscription
@repo.euthanizeCollection(this)
cache: ->
###
Cache collection
###
@repo.cacheCollection @
invalidateCache: ->
###
Invalidtes collection's cache.
Call in case of an emergency!
Returns promise
###
#@_totalCount = null #force getPagingInfo to make request
@repo.invalidateCollectionCache(@name)
isConsistent: (array) ->
###
Return true if collection or array has no gaps
###
if !array
if @_loadedStart > @_loadedEnd and @_models.length > 0
return false
modelsEnd = @_models.length - 1
lastIndex = if modelsEnd < @_loadedEnd then modelsEnd else @_loadedEnd
if lastIndex >= 0
for i in [@_loadedStart..lastIndex]
if @_models[i] == undefined
return false
else
for model in array
if model == undefined
return false
return true
clearLastQueryTime: ->
@_lastQueryTime = 0
getLastQueryTime: ->
if @_lastQueryTime then @_lastQueryTime else 0
getLastQueryTimeDiff: ->
(new Date).getTime() - @getLastQueryTime()
sync: (returnMode, start, end, callback) ->
###
Initiates synchronization of the collection with some backend; fires callback and completes resulting future
denending of given return mode.
It's possible to call method:
* without any arguments - whole range in :sync mode, completion by returning future.
* without first three arguments - the same but with callback
* without start and end arguments - whole range in the given mode
* returnMode must be provided if it's necessary to pass range options (start and end).
* start and end must be passed either both or none
@param (optional) String returnMode :sync - return only after sync with server
:async - return immidiately if collection is initialized before,
sync in background
:now - return immidiately even if collection is not ever syncronized before,
sync in background
:cache - return cached collection if initialized (without syncing),
or perform like :sync otherwise
@param (optional)Int start starting position of the required range
@param (optional)Int end ending position of the required range
@param (optional)Function(this) callback callback to call on sync completion depending on the return mode.
@return Future(this)
###
if _.isFunction(returnMode)
callback = returnMode
returnMode = ':sync'
start = end = undefined
else if _.isFunction(start)
callback = start
start = end = undefined
returnMode = ':cache' if returnMode == ':cache-async'
returnMode ?= ':sync'
cacheMode = (returnMode == ':cache')
# Special case - fixed collection
if @_fixed
resultPromise = Future.single('Collection::sync resultPromise')
resultPromise.resolve(this)
callback?(this)
return resultPromise
# this future is resolved by cache results or server results - which come first
firstResultPromise = Future.single('Collection::sync firstResultPromise')
# we should wait for range information from the local cache before staring remote sync query
rangeAdjustPromise = Future.single('Collection::sync rangeAdjustPromise')
# special promise for cache mode to avoid running remote sync if unnecessary
activateSyncPromise = Future.single('Collection::sync activateSyncPromise')
activateSyncPromise.resolve(true) if not cacheMode
if not @_initialized
# try to load local storage cache only when syncing first time
@_getModelsFromLocalCache(start, end, rangeAdjustPromise).done (models, syncStart, syncEnd) =>
Defer.nextTick => # give remote sync a chance
if not firstResultPromise.completed()
@_fillModelList(models, syncStart, syncEnd) if not @_initialized # the check is need in case of parallel cache trial
firstResultPromise.resolve(this)
activateSyncPromise.resolve(false) if cacheMode # remote sync is not necessary in :cache mode
.fail (error) =>
activateSyncPromise.resolve(true) if cacheMode # cache failed, need to remote sync even in :cache mode
else # if @_initialized
rangeAdjustPromise.resolve(start, end)
if cacheMode
# in :cache mode we need to check if requested range is already loaded into the collection's payload
if start? and end?
if start >= @_loadedStart and end <= @_loadedEnd
activateSyncPromise.resolve(false)
firstResultPromise.resolve(this)
else
activateSyncPromise.resolve(true)
else
if @_hasLimits == false
activateSyncPromise.resolve(false)
firstResultPromise.resolve(this)
else
activateSyncPromise.resolve(true)
# sync with backend
# special promise for :sync mode completion
syncPromise = activateSyncPromise.then (activate) =>
if activate
# wait for range adjustment from the local cache
rangeAdjustPromise.then (syncStart, syncEnd) =>
@_enqueueQuery(syncStart, syncEnd) # avoid repeated refresh-query
.then =>
firstResultPromise.resolve(this) if not firstResultPromise.completed()
this
else
this
# handling different behaviours of return modes
resultPromise = Future.single('Collection::sync resultPromise')
switch returnMode
when ':sync' then resultPromise.when(syncPromise)
when ':async'
if start? and end?
if start >= @_loadedStart and end <= @_loadedEnd
resultPromise.resolve(this)
else
resultPromise.when(firstResultPromise)
else
if @_hasLimits == false
resultPromise.resolve(this)
else
resultPromise.when(firstResultPromise)
when ':now' then resultPromise.resolve(this)
when ':cache' then resultPromise.when(firstResultPromise)
resultPromise.done =>
callback?(this)
scanModels: (scannedFields, searchedText, limit) ->
###
Scans models in current collection for searched Text in scannedFields and return object of their clones
@param Array scannedFields - fields to be scanned
@param String searchedText - searched text
@return object { <id>: <model>, ... }
###
result = {}
return result if !searchedText
amount = 0
searchedText = searchedText.toLowerCase()
for model in @_models
for fieldName in scannedFields
if model[fieldName] && !result[model.id] && String(model[fieldName]).toLowerCase().indexOf(searchedText) > -1
result[model.id] = _.clone model
break
if limit && amount >= limit
break
result
have: (id) ->
!!@_byId[id]
get: (id) ->
if @_byId[id]?
@_byId[id]
else
throw new ModelNotExists("There is no model with id = #{ id } in collection [#{ @debug() }]!")
toArray: ->
# This method returns array of loaded models.
# Warning! Probably you should not use this function for paged collections, but getPage()
if @_pageSize > 0
_console.warn('Warning, collection.toArray() was used for paged collection!', @debug())
@_models
isInitialized: ->
###
Indicates that the collection is already synchronized at least once.
@return Boolean
###
@_initialized
checkNewModel: (model, emitModelChangeExcept = true) ->
###
Checks if the new model is related to this collection. If it is reloads collection from the backend.
@param Model model the new model
###
id = parseInt(if _.isObject(model) then model.id else model)
if (not @_id or (not isNaN(id) and parseInt(@_id) == id)) and @hasActiveSubscriptions()
@refresh(id, @_defaultRefreshPages, 0, emitModelChangeExcept)
_reorderModelsLocal: ->
###
Rearrange collection models according to the orderBy options.
###
if @_orderBy? and @_orderBy != ''
iterator = @_orderBy
else if @constructor.orderBy? and @constructor.orderBy != ''
iterator = @constructor.orderBy
else
return
sortDesc = false
if _.isString(iterator)
first = iterator.substr(0, 1)
sortDesc = (first == '-')
iterator = iterator.substr(1) if first == '-' or first == '+'
else
sortDesc = true if @constructor.orderDir == ':desc'
@_models = _.sortBy(@_models, iterator)
@_models.reverse() if sortDesc
_reindexModels: ->
###
Rebuilds useful index of the models by their id.
###
@_byId = {}
for m in @_models
if m != undefined
@_byId[m.id] = m
hasActiveSubscriptions: ->
###
Returns true if refresh allowed, which means
1. there's no other refreshes in progress
2. the collection is not fixed
3. the collection has at least one 'change' subscription
###
if @_fixed #or @_refreshInProgress
false
else if not @_hasActiveChangeSubscriptions()
false
else
true
partialRefresh: (startPage, maxPages, minRefreshInterval = 0) ->
###
Reloads olny maxPages pages of the collection only if the collection hasn't been refreshed for required interval
Useful for potentilally huge collections
###
# _console.log "#{ @repo.restResource } partialRefresh: (startPage=#{startPage}, maxPages=#{maxPages}, minRefreshInterval=#{minRefreshInterval})"
startPage = Number(startPage)
maxPages = Number(maxPages)
# This is actually for debugging purposes
if isNaN(startPage) or isNaN(maxPages) or startPage < 1 or maxPages <1
return _console.error('collection.partialRefresh called with wront parameters startPage, maxPages',
startPage,
maxPages,
(new Error()).stack)
if minRefreshInterval >= 0 and @getLastQueryTimeDiff() > minRefreshInterval
@_refreshInProgress = true
if not @_pageSize
@_fullReload()
else
@_simplePageRefresh(startPage, maxPages)
refresh: (currentId, maxPages = @_defaultRefreshPages, minRefreshInterval = 0, emitModelChangeExcept = true) ->
###
Reloads currently loaded part of collection from the backend.
By the way triggers change events for every changed model and for the collection if there are any changes.
todo: support of single-model collections
@param int currentId - id of currently used model (selected or showed),
@param int maxPages - amount of pages to be refreshed, the rest of the collection will be cleaned
if currentId and pageSize are defined, refresh will start from page, containing the currentId model, going up and down
###
#_console.log "#{ @repo.restResource } refresh: (currentId=#{currentId}, emitModelChangeExcept=#{emitModelChangeExcept}, maxPages=#{maxPages})"
# Try to catch some architectural errors
if isNaN(Number(currentId))
_console.error('collection.refresh called with wrong parameter currentId', currentId, (new Error()).stack)
return
if maxPages < 1
_console.error('collection.refresh called with wrong parameter maxPages', maxPages, (new Error()).stack)
return if not (minRefreshInterval >= 0 and @getLastQueryTimeDiff() > minRefreshInterval)
@_refreshInProgress = true
# Refresh all models at once if no paging used
if not @_pageSize
@_fullReload()
else
# Collection boundaries
startPage = Math.floor(@_loadedStart / @_pageSize) + 1
endPage = Math.ceil(@_loadedEnd / @_pageSize)
# Check if the model is already in the collection, which means we know where to start
if @_byId[currentId]
modelIndex = _.indexOf @_models, @_byId[currentId]
modelPage = Math.ceil((modelIndex + 1) / @_pageSize)
@_sophisticatedRefreshPage(modelPage, startPage, endPage, maxPages)
else
# If model is not in the collection than we have to check if the model belongs to the collection
# The best way to do this is to make a paging request
@getPagingInfo(currentId, true).failAloud().done (paging) =>
if paging.pages == 0
# special case, when collection nullifies on server
@_replaceModelList([], @_loadedStart, @_loadedEnd)
@_refreshInProgress = false
else if paging.selectedPage > 0
# Don't refresh collection if currentId is not belonged to it
@_sophisticatedRefreshPage(paging.selectedPage, startPage, endPage, maxPages)
else
@_refreshInProgress = false
_fullReload: ->
###
Completely reloads all collection at once
###
# _console.log '_fullReload'
queryParams = @_buildRefreshQueryParams()
@repo.query queryParams, (models) =>
@_replaceModelList(models, queryParams.start, queryParams.end)
@_refreshInProgress = false
_simplePageRefresh: (startPage, maxPages, loadedPages = 0) ->
###
Simple refreshes few pages one by one
###
# _console.log "#{ @repo.restResource } _simplePageRefresh: (startPage=#{startPage}, maxPages=#{maxPages}, loadedPages=#{loadedPages}) ->"
if startPage < 1 or maxPages < 1
_console.error('collection._simplePageRefresh got bad parameters.')
else
start = (startPage - 1) * @_pageSize
end = startPage * @_pageSize - 1
# We'll continue refreshing if [start,end] intersects with [@_loadedStart, @_loadedEnd]
if (start <= @_loadedStart <= end or start <= @_loadedEnd <= end) and loadedPages + 1 <= maxPages
@_enqueueQuery(start, end, true).failAloud().done =>
@_simplePageRefresh(startPage + 1, maxPages, loadedPages + 1)
else
@_refreshInProgress = false
_sophisticatedRefreshPage: (page, startPage, endPage, maxPages = @_defaultRefreshPages, direction = 'down', loadedPages = 0) ->
# _console.log "#{ @repo.restResource } _sophisticatedRefreshPage: (page=#{page}, startPage=#{startPage}, endPage=#{endPage}, maxPages=#{maxPages}, direction=#{direction}, loadedPages=#{loadedPages})"
start = (page - 1) * @_pageSize
end = page * @_pageSize - 1
if page > 0 and loadedPages < maxPages and (start <= @_loadedStart <= end or start <= @_loadedEnd <= end)
@_enqueueQuery(start, end, true).done =>
if not @_refreshReachedTop
@_refreshReachedTop = page == startPage
if not @_refreshReachedBottom
@_refreshReachedBottom = page == endPage
if @_refreshReachedTop
direction = 'down'
else if @_refreshReachedBottom
direction = 'up'
else
direction = if direction == 'up' then 'down' else 'up'
@_topPage = page if not @_topPage
@_bottomPage = page if not @_bottomPage
if direction == 'up'
page = @_topPage = @_topPage - 1
else
page = @_bottomPage = @_bottomPage + 1
@_sophisticatedRefreshPage(page, startPage, endPage, maxPages, direction, loadedPages + 1)
.fail (message) =>
@_topPage = 0
@_bottomPage = 0
@_refreshReachedTop = false
@_refreshReachedBottom = false
@_refreshInProgress = false
_console.error('collection._sophisticatedRefreshPage _enqueueQuery error: ', message)
else
# total flush
@_topPage = 0
@_bottomPage = 0
@_refreshReachedTop = false
@_refreshReachedBottom = false
@_refreshInProgress = false
_buildRefreshQueryParams: ->
###
Builds backend query params for the currently defined collection params to refresh collection items.
@return Object key-value params for the ModelRepo::query() method
###
if @_id
result =
id: @_id
fields: @_fields
requestParams: @_requestParams
accessPoint: @_accessPoint
orderBy: @_orderBy
else
result =
orderBy: @_orderBy
fields: @_fields
filter: @_filter
requestParams: @_requestParams
accessPoint: @_accessPoint
if @_filterType == ':backend'
result.filterId = @_filterId
result.filterParams = @_filterParams
if @_hasLimits
result.start = @_loadedStart
result.end = @_loadedEnd
result
_hasActiveChangeSubscriptions: ->
return false if not @_subscriptions
return true if @_subscriptions.change and @_subscriptions.change.length > 0
for topic, subscriptions of @_subscriptions
return true if subscriptions.length > 0 and topic.substr(-6) == 'change'
false
addModel: (model, position = ':tail') ->
###
Manually adds model into the collection and reorders the list of the models.
Emits 'change' event for the collection.
@param Model model the new or updated model
@param String position ':head' or ':tail' append
###
position = ':tail' if position != ':head'
model.setCollection(this)
@_models = _.without(@_models, @_byId[model.id]) if @_byId[model.id]?
if position == ':tail'
@_models.push(model)
else
@_models.unshift(model)
@_reorderModelsLocal()
@_byId[model.id] = model
#calculate model's page
modelPage = 0
if !isNaN(parseInt(@_pageSize)) && @_pageSize > 0
modelIndex = _.indexOf @_models, model
modelPage = Math.ceil((modelIndex + 1) / @_pageSize)
changedModels = {}
changedModels[model.id] = model
@emit 'change', {firstPage: modelPage, lastPage: modelPage, models: changedModels}
_fillModelList: (models, start, end) ->
###
Fills model list with initial data.
Differs from _replaceModelList() in behaviour of firing change events for models and collection. This method
doesn't fire any events. Therefore it should be used only for initial filling.
@param Array[Model] models list of models
@param (optional)Int start starting index of the loading range
@param (optional)Int end ending index of the loading range
###
if start? and end?
# appending new models to the collection according to the paging options
for model, i in models
if model
model.setCollection(this)
@_models[start + i] = model
@_loadedStart = start if start < @_loadedStart
@_loadedEnd = end if end > @_loadedEnd
@_hasLimits = (@_hasLimits != false)
else
@_models = models
@_loadedStart = 0
@_loadedEnd = if models.length == 0 then 0 else models.length - 1
@_hasLimits = false
@_totalCount = models.length
model.setCollection(this) for model in @_models
@_reindexModels()
@_initialized = true
_replaceModelList: (newList, start, end, emitModelChangeExcept = true) ->
###
Substitutes part of list of models with the new ones comparing them by the way and triggering according events.
If start and end arguments are not given, then the whole list is replaced starting from index 0.
@param Array[Model] newList list of new models
@param (optional)Int start starting index of the destination list, from which should replacement started
@param (optional)Int end index of last item to replace
###
# This means that previously collection was empty and something new has arrived
oldListCount = @_models.length
oldList = _.clone(@_models)
if (start? and end?) and (start < end)
###
#in case of refreshing, we'll just replace the list
if start == @_loadedStart && end == @_loadedEnd
@_fillModelList newList
return true
###
loadingStart = start
loadingEnd = end
@_models = _.clone(@_models)
else
loadingStart = 0
loadingEnd = newList.length - 1
@_models = []
firstChangedIndex = oldListCount
lastChangedIndex = 0
deleted = false
deletedModels = {}
changed = false
changedModels = {}
newListIds = {}
for item in newList
newListIds[item.id] = item
for model in oldList
# Бывает так, что в списке моделей есть пропуски... Надо с этим разобраться.
continue if not model
if not newListIds[model.id]
deletedModels[model.id] = model
deleted = true
changed = true
targetIndex = loadingStart - 1
# appending/replacing new models to the collection according to the paging options
for model, i in newList
model.setCollection(this)
targetIndex = loadingStart + i
if @_byId[model.id]? and @_compareModels(model, @_byId[model.id])
changed = true
firstChangedIndex = targetIndex if targetIndex < firstChangedIndex
lastChangedIndex = targetIndex if targetIndex > lastChangedIndex
changedModels[model.id] = model
@emit "model.#{ model.id }.change", model
@emitModelChangeExcept(model) if emitModelChangeExcept
if not oldList[targetIndex]? or model.id != oldList[targetIndex].id
changed = true
changedModels[model.id] = model
firstChangedIndex = targetIndex if targetIndex < firstChangedIndex
lastChangedIndex = targetIndex if targetIndex > lastChangedIndex
@_models[targetIndex] = model
if targetIndex < loadingEnd
@_models.splice(targetIndex + 1, loadingEnd - targetIndex)
@_loadedStart = loadingStart if loadingStart < @_loadedStart
if loadingEnd > @_loadedEnd
@_loadedEnd = loadingEnd
else if loadingEnd =-1 and @_loadedEnd == -1
@_loadedEnd = 0
@_reindexModels()
@_initialized = true
# in situation when newList is empty, we must emit change event
if newList.length < oldListCount
changed = true
firstChangedIndex = newList.length if newList.length < firstChangedIndex
lastChangedIndex = oldListCount if oldListCount > lastChangedIndex
firstPage = 0
lastPage = 0
if !isNaN(parseInt(@_pageSize)) && @_pageSize > 0
firstPage = Math.ceil((firstChangedIndex + 1) / @_pageSize)
lastPage = Math.ceil((lastChangedIndex + 1) / @_pageSize)
@emit 'change', {firstPage: firstPage, lastPage: lastPage, models: changedModels} if changed
@emit 'delete', {models: deletedModels} if deleted
if not (start? and end?)
@_totalCount = newList.length
else if changed
@_totalCount = null # should be asked from the backend again just in case
@repo.cacheCollection(this)
_compareModels: (model1, model2) ->
###
Deeply compares two models using only fields of this collection.
@param Model model1
@param Model model2
@return Boolean true if models differ, false if they are the same
###
return true if model1.id != model2.id
for field in model1.getDefinedFieldNames()
if @repo.hasFieldCompareFunction(field)
return true if @repo.fieldCompareFunction(field, model1[field], model2[field])
else if field != 'id' and not @_modelsEq(model1[field], model2[field])
return true
return false
_modelsEq: (a, b) ->
###
Port of underscore's isEqual (to be more precise, eq) function with cutted down support of recursive structures
and cutted down checking of fields in b that doesn't exists in a.
###
# Undefined models are never equal
return false if a == undefined || b == undefined
# Identical objects are equal. `0 === -0`, but they aren't identical.
# See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
return a != 0 || 1 / a == 1 / b if a == b
# A strict comparison is necessary because `null == undefined`.
return a == b if a == null || b == null
# Unwrap any wrapped objects.
a = a._wrapped if a._chain
b = b._wrapped if b._chain
# Invoke a custom `isEqual` method if one is provided.
return a.isEqual(b) if a.isEqual && _.isFunction(a.isEqual)
return b.isEqual(a) if b.isEqual && _.isFunction(b.isEqual)
# Compare `[[Class]]` names.
className = toString.call(a)
return false if className != toString.call(b)
switch className
# Strings, numbers, dates, and booleans are compared by value.
when '[object String]'
# Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
# equivalent to `new String("5")`.
return a == String(b)
when '[object Number]'
# `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
# other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b)
when '[object Date]', '[object Boolean]'
# Coerce dates and booleans to numeric primitive values. Dates are compared by their
# millisecond representations. Note that invalid dates with millisecond representations
# of `NaN` are not equivalent.
return +a == +b;
# RegExps are compared by their source patterns and flags.
when '[object RegExp]'
return a.source == b.source && \
a.global == b.global && \
a.multiline == b.multiline && \
a.ignoreCase == b.ignoreCase