-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackbone-reaction.js
1788 lines (1625 loc) · 54.4 KB
/
backbone-reaction.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
/*!
* backbone-reaction v0.12.0
* https://github.com/jhudson8/backbone-reaction
*
* Copyright (c) 2014 Joe Hudson<joehud_AT_gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
Container script which includes the following:
https://github.com/jhudson8/react-mixin-manager v0.8.0
https://github.com/jhudson8/react-events v0.5.2
https://github.com/jhudson8/backbone-xhr-events v0.8.1
https://github.com/jhudson8/react-backbone v0.13.2
*/
(function(main) {
if (typeof define === 'function' && define.amd) {
define([], function() {
// with AMD
// require(
// ['react', 'backbone', 'underscore', react-backbone/with-deps'],
// function(React, Backbone, underscore, reactBackbone) {
// reactBackbone(React, Backbone, _);
// });
return main;
});
} else if (typeof exports !== 'undefined' && typeof require !== 'undefined') {
// with CommonJS
// require('react-backbone/with-deps')(require('react'), require('backbone'), require('underscore'));
module.exports = main;
} else {
main(React, Backbone, _);
}
})(function(React, Backbone, _) {
(function() {
/*******************
* backbone-xhr-events
* https://github.com/jhudson8/backbone-xhr-events
********************/
// ANY OVERRIDES MUST BE DEFINED BEFORE LOADING OF THIS SCRIPT
// Backbone.xhrCompleteEventName: event triggered on models when all XHR requests have been completed
var xhrCompleteEventName = Backbone.xhrCompleteEventName = Backbone.xhrCompleteEventName || 'xhr:complete';
// the model attribute which can be used to return an array of all current XHR request events
var xhrLoadingAttribute = Backbone.xhrModelLoadingAttribute = Backbone.xhrModelLoadingAttribute || 'xhrActivity';
// Backbone.xhrEventName: the event triggered on models and the global bus to signal an XHR request
var xhrEventName = Backbone.xhrEventName = Backbone.xhrEventName || 'xhr';
// Backbone.xhrGlobalAttribute: global event handler attribute name (on Backbone) used to subscribe to all model xhr events
var xhrGlobalAttribute = Backbone.xhrGlobalAttribute = Backbone.xhrGlobalAttribute || 'xhrEvents';
// initialize the global event bus
var globalXhrBus = Backbone[xhrGlobalAttribute] = _.extend({}, Backbone.Events);
var SUCCESS = 'success';
var ERROR = 'error';
var Context = function(method, model, options) {
this.method = method;
this.model = model;
this.options = options;
}
Context.prototype.abort = function() {
if (!this.aborted) {
this.aborted = true;
this.preventDefault = true;
if (this.xhr) {
this.xhr.abort();
}
}
}
_.extend(Context.prototype, Backbone.Events);
// allow backbone to send xhr events on models
var _sync = Backbone.sync;
Backbone.sync = function (method, model, options) {
options = options || {};
// Ensure that we have a URL.
if (!options.url) {
options.url = _.result(model, 'url');
}
var context = initializeXHRLoading(method, model, model, options);
if (context.preventDefault) {
// it is assumed that either context.options.success or context.options.error will be called
return;
}
var xhr = _sync.call(this, method, model, options);
context.xhr = xhr;
return xhr;
};
// provide helper flags to determine model fetched status
globalXhrBus.on(xhrEventName + ':read', function (model, events) {
events.on(SUCCESS, function () {
model.hasBeenFetched = true;
model.hadFetchError = false;
});
events.on(ERROR, function () {
model.hadFetchError = true;
});
});
// execute the callback directly if the model is fetch
// initiate a fetch with this callback as the success option if not fetched
// or plug into the current fetch if in progress
Backbone.Model.prototype.whenFetched = Backbone.Collection.whenFetched = function(success, error) {
var model = this;
function successWrapper() {
success(model);
}
if (this.hasBeenFetched) {
return success(this);
}
// find current fetch call (if any)
var _fetch = _.find(this[xhrLoadingAttribute], function(req) {
return req.method === 'read';
});
if (_fetch) {
_fetch.on('success', successWrapper);
if (error) {
_fetch.on('error', error);
}
} else {
this.fetch({ success: successWrapper, error: error });
}
}
// forward all or some XHR events from the source object to the dest object
Backbone.forwardXhrEvents = function (source, dest, typeOrCallback) {
var handler = handleForwardedEvents(!_.isFunction(typeOrCallback) && typeOrCallback);
if (_.isFunction(typeOrCallback)) {
// forward the events *only* while the function is executing wile keeping "this" as the context
try {
source.on(xhrEventName, handler, dest);
typeOrCallback.call(this);
} finally {
source.off(xhrEventName, handler, dest);
}
} else {
var eventName = typeOrCallback ? (xhrEventName + ':') + typeOrCallback : xhrEventName;
source.on(eventName, handler, dest);
}
}
Backbone.stopXhrForwarding = function (source, dest, type) {
var handler = handleForwardedEvents(type),
eventName = type ? (xhrEventName + ':') + type : xhrEventName;
source.off(xhrEventName, handler, dest);
}
var _eventForwarders = {};
function handleForwardedEvents(type) {
type = type || '_all';
var func = _eventForwarders[type];
if (!func) {
// cache it so we can unbind when we need to
func = function (eventName, events) {
if (type !== '_all') {
// if the event is already scoped, the event type will not be provided as the first parameter
options = events;
events = eventName;
eventName = type;
}
// these events will be called because we are using the same options object as the source call
initializeXHRLoading(events.method, this, events.model, events.options);
}
_eventForwarders[type] = func;
}
return func;
}
// set up the XHR eventing behavior
// "model" is to trigger events on and "sourceModel" is the model to provide to the success/error callbacks
// these are the same unless there is event forwarding in which case the "sourceModel" is the model that actually
// triggered the events and "model" is just forwarding those events
function initializeXHRLoading(method, model, sourceModel, options) {
var loads = model[xhrLoadingAttribute] = model[xhrLoadingAttribute] || [],
eventName = options && options.event || method,
context = new Context(method, sourceModel, options);
var scopedEventName = xhrEventName + ':' + eventName;
model.trigger(xhrEventName, eventName, context);
model.trigger(scopedEventName, context);
if (model === sourceModel) {
// don't call global events if this is XHR forwarding
globalXhrBus.trigger(xhrEventName, eventName, model, context);
globalXhrBus.trigger(scopedEventName, model, context);
}
// allow for 1 last override
var _beforeSend = options.beforeSend;
options.beforeSend = function(xhr, settings) {
context.xhr = xhr;
context.settings = settings;
if (_beforeSend) {
var rtn = _beforeSend.call(this, xhr, settings);
if (rtn === false) {
return rtn;
}
}
context.trigger('before-send', xhr, settings, context);
if (context.preventDefault) {
return false;
}
loads.push(context);
};
function onComplete(type) {
var _type = options[type];
// success: (data, status, xhr); error: (xhr, type, error)
options[type] = function (p1, p2, p3) {
if (type === SUCCESS && !context.preventDefault) {
// trigger the "data" event which allows manipulation of the response before any other events or callbacks are fired
context.trigger('after-send', p1, p2, p3, type, context);
p1 = context.data || p1;
// if context.preventDefault is true, it is assumed that the option success or callback will be manually called
if (context.preventDefault) {
return;
}
}
var _args = arguments;
// options callback
try {
if (_type) {
_type.call(this, p1, p2, p3);
}
}
finally {
// remove the load entry
var index = loads.indexOf(context);
if (index >= 0) {
loads.splice(index, 1);
}
// if there are no more cuncurrent XHRs, model[xhrLoadingAttribute] should always be undefind
if (loads.length === 0) {
model[xhrLoadingAttribute] = undefined;
model.trigger(xhrCompleteEventName, context);
}
}
// trigger the success/error event
var args = (type === SUCCESS) ? [type, context] : [type, p1, p2, p3, context];
context.trigger.apply(context, args);
// trigger the complete event
args.splice(0, 0, 'complete');
context.trigger.apply(context, args);
};
}
onComplete(SUCCESS);
onComplete(ERROR);
return context;
}
/*******************
* end of backbone-xhr-events
********************/
})();
(function() {
/*******************
* react-mixin-manager
* https://github.com/jhudson8/react-mixin-manager
********************/
function setState(state, context) {
if (context.isMounted()) {
context.setState(state);
} else if (context.state) {
for (var name in state) {
context.state[name] = state[name];
}
} else {
// if we aren't mounted, we will get an exception if we try to set the state
// so keep a placeholder state until we're mounted
// this is mainly useful if setModel is called on getInitialState
var _state = context.__temporary_state || {};
for (var name in state) {
_state[name] = state[name];
}
context.__temporary_state = _state;
}
}
function getState(key, context) {
var state = context.state,
initState = context.__temporary_state;
return (state && state[key]) || (initState && initState[key]);
}
/**
* return the normalized mixin list
* @param values {Array} list of mixin entries
* @param index {Object} hash which contains a truthy value for all named mixins that have been added
* @param initiatedOnce {Object} hash which collects mixins and their parameters that should be initiated once
* @param rtn {Array} the normalized return array
*/
function get(values, index, initiatedOnce, rtn) {
/**
* add the named mixin and all un-added dependencies to the return array
* @param the mixin name
*/
function addTo(name) {
var indexName = name,
match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/),
params = match && match[2];
name = match && match[1] || name;
if (!index[indexName]) {
if (params) {
// there can be no function calls here because of the regex match
params = eval('[' + params + ']');
}
var mixin = React.mixins._mixins[name],
checkAgain = false,
skip = false;
if (mixin) {
if (typeof mixin === 'function') {
if (React.mixins._initiatedOnce[name]) {
initiatedOnce[name] = (initiatedOnce[name] || []);
initiatedOnce[name].push(params);
skip = true;
} else {
mixin = mixin.apply(this, params || []);
checkAgain = true;
}
} else if (params) {
throw new Error('the mixin "' + name + '" does not support parameters');
}
get(React.mixins._dependsOn[name], index, initiatedOnce, rtn);
get(React.mixins._dependsInjected[name], index, initiatedOnce, rtn);
index[indexName] = true;
if (checkAgain) {
get([mixin], index, initiatedOnce, rtn);
} else if (!skip) {
rtn.push(mixin);
}
} else {
throw new Error('invalid mixin "' + name + '"');
}
}
}
function handleMixin(mixin) {
if (mixin) {
if (Array.isArray(mixin)) {
// flatten it out
get(mixin, index, initiatedOnce, rtn);
} else if (typeof mixin === 'string') {
// add the named mixin and all of it's dependencies
addTo(mixin);
} else {
// just add the mixin normally
rtn.push(mixin);
}
}
}
if (Array.isArray(values)) {
for (var i = 0; i < values.length; i++) {
handleMixin(values[i]);
}
} else {
handleMixin(values);
}
}
/**
* add the mixins that should be once initiated to the normalized mixin list
* @param mixins {Object} hash of mixins keys and list of its parameters
* @param rtn {Array} the normalized return array
*/
function getInitiatedOnce(mixins, rtn) {
/**
* added once initiated mixins to return array
*/
function addInitiatedOnce(mixin, params) {
mixin = mixin.apply(this, params || []);
rtn.push(mixin);
}
for (var m in mixins) {
if (mixins.hasOwnProperty(m)) {
addInitiatedOnce(React.mixins._mixins[m], mixins[m]);
}
}
}
// allow for registered mixins to be extract just by using the standard React.createClass
var _createClass = React.createClass;
React.createClass = function(spec) {
if (spec.mixins) {
spec.mixins = React.mixins.get(spec.mixins);
}
return _createClass.apply(React, arguments);
};
function addMixin(name, mixin, depends, override, initiatedOnce) {
var mixins = React.mixins;
if (!override && mixins._mixins[name]) {
return;
}
mixins._dependsOn[name] = depends.length && depends;
mixins._mixins[name] = mixin;
if (initiatedOnce) {
mixins._initiatedOnce[name] = true;
}
}
function GROUP() {
// empty function which is used only as a placeholder to list dependencies
}
function mixinParams(args, override) {
var name,
options = args[0],
initiatedOnce = false;
if (typeof(options) === 'object') {
name = options.name;
initiatedOnce = options.initiatedOnce;
} else {
name = options;
}
if (!name || !name.length) {
throw new Error('the mixin name hasn\'t been specified');
}
if (Array.isArray(args[1])) {
return [name, args[1][0], Array.prototype.slice.call(args[1], 1), override, initiatedOnce];
} else {
return [name, args[1], Array.prototype.slice.call(args, 2), override, initiatedOnce]
}
}
React.mixins = {
/**
* return the normalized mixins. there can be N arguments with each argument being
* - an array: will be flattened out to the parent list of mixins
* - a string: will match against any registered mixins and append the correct mixin
* - an object: will be treated as a standard mixin and returned in the list of mixins
* any string arguments that are provided will cause any dependent mixins to be included
* in the return list as well
*/
get: function() {
var rtn = [],
index = {},
initiatedOnce = {};
get(Array.prototype.slice.call(arguments), index, initiatedOnce, rtn);
getInitiatedOnce(initiatedOnce, rtn);
return rtn;
},
/**
* Inject dependencies that were not originally defined when a mixin was registered
* @param name {string} the main mixin name
* @param (any additional) {string} dependencies that should be registered against the mixin
*/
inject: function(name) {
var l = this._dependsInjected[name];
if (!l) {
l = this._dependsInjected[name] = [];
}
l.push(Array.prototype.slice.call(arguments, 1));
},
alias: function(name) {
addMixin(name, GROUP, Array.prototype.slice.call(arguments, 1), false);
},
add: function(options, mixin) {
addMixin.apply(this, mixinParams(arguments, false));
},
replace: function(options, mixin) {
addMixin.apply(this, mixinParams(arguments, true));
},
exists: function(name) {
return this._mixins[name] || false;
},
_dependsOn: {},
_dependsInjected: {},
_mixins: {},
_initiatedOnce: {}
};
/**
* mixin that exposes a "deferUpdate" method which will call forceUpdate after a setTimeout(0) to defer the update.
* This allows the forceUpdate method to be called multiple times while only executing a render 1 time. This will
* also ensure the component is mounted before calling forceUpdate.
*
* It is added to mixin manager directly because it serves a purpose that benefits when multiple plugins use it
*/
React.mixins.add('deferUpdate', {
getInitialState: function() {
// ensure that the state exists because we don't want to call setState (which will cause a render)
return {};
},
deferUpdate: function() {
var state = this.state;
if (!state._deferUpdate) {
state._deferUpdate = true;
var self = this;
setTimeout(function() {
delete state._deferUpdate;
if (self.isMounted()) {
self.forceUpdate();
}
}, 0);
}
}
});
/**
* very simple mixin that ensures that the component state is an object. This is useful if you
* know a component will be using state but won't be initialized with a state to prevent a null check on render
*/
React.mixins.add('state', {
getInitialState: function() {
return {};
},
componentWillMount: function() {
// not directly related to this mixin but all of these mixins have this as a dependency
// if setState was called before the component was mounted, the actual component state was
// not set because it might not exist. Convert the pretend state to the real thing
// (but don't trigger a render)
var _state = this.__temporary_state;
if (_state) {
for (var key in _state) {
this.state[key] = _state[key];
}
delete this.__temporary_state;
}
}
});
React.mixins.setState = setState;
React.mixins.getState = getState;
/*******************
* end of react-mixin-manager
********************/
})();
(function() {
/*******************
* react-events
* https://github.com/jhudson8/react-events
********************/
var handlers = {},
patternHandlers = [],
splitter = /^([^:]+):?(.*)/,
specialWrapper = /^\*([^\(]+)\(([^)]*)\):(.*)/,
noArgMethods = ['forceUpdate'],
setState = React.mixins.setState,
getState = React.mixins.getState;
/**
* Allow events to be referenced in a hierarchical structure. All parts in the
* hierarchy will be appended together using ":" as the separator
* window: {
* scroll: 'onScroll',
* resize: 'onResize'
* }
* will return as
* {
* 'window:scroll': 'onScroll',
* 'window:resize': 'onResize'
* }
}
*/
function normalizeEvents(events, rtn, prefix) {
rtn = rtn || {};
if (prefix) {
prefix += ':';
} else {
prefix = '';
}
var value, valueType;
for (var key in events) {
value = events[key];
valueType = typeof value;
if (valueType === 'string' || valueType === 'function') {
rtn[prefix + key] = value;
} else if (value) {
normalizeEvents(value, rtn, prefix + key);
}
}
return rtn;
}
/**
* Internal model event binding handler
* (type(on|once|off), {event, callback, context, target})
*/
function manageEvent(type, data) {
var eventsParent = this;
var _data = {
type: type
};
for (var name in data) {
_data[name] = data[name];
}
var watchedEvents = React.mixins.getState('__watchedEvents', this);
if (!watchedEvents) {
watchedEvents = [];
setState({
__watchedEvents: watchedEvents
}, this);
}
_data.context = _data.context || this;
watchedEvents.push(_data);
// bind now if we are already mounted (as the mount function won't be called)
var target = getTarget(_data.target, this);
if (this.isMounted()) {
if (target) {
target[_data.type](_data.event, _data.callback, _data.context);
}
}
if (type === 'off') {
var watchedEvent;
for (var i=0; i<watchedEvents.length; i++) {
watchedEvent = watchedEvents[i];
if (watchedEvent.event === data.event &&
watchedEvent.callback === data.callback &&
getTarget(watchedEvent.target, this) === target) {
watchedEvents.splice(i, 1);
}
}
}
}
// bind all registered events to the model
function _watchedEventsBindAll(context) {
var watchedEvents = getState('__watchedEvents', context);
if (watchedEvents) {
var data;
for (var name in watchedEvents) {
data = watchedEvents[name];
var target = getTarget(data.target, context);
if (target) {
target[data.type](data.event, data.callback, data.context);
}
}
}
}
// unbind all registered events from the model
function _watchedEventsUnbindAll(keepRegisteredEvents, context) {
var watchedEvents = getState('__watchedEvents', context);
if (watchedEvents) {
var data;
for (var name in watchedEvents) {
data = watchedEvents[name];
var target = getTarget(data.target, context);
if (target) {
target.off(data.event, data.callback, data.context);
}
}
if (!keepRegisteredEvents) {
setState({
__watchedEvents: []
}, context);
}
}
}
function getTarget(target, context) {
if (typeof target === 'function') {
return target.call(context);
}
return target;
}
/*
* wrapper for event implementations - includes on/off methods
*/
function createHandler(event, callback, context, dontWrapCallback) {
if (!dontWrapCallback) {
var _callback = callback,
noArg;
if (typeof callback === 'object') {
// use the "callback" attribute to get the callback function. useful if you need to reference the component as "this"
_callback = callback.callback.call(this);
}
if (typeof callback === 'string') {
noArg = (noArgMethods.indexOf(callback) >= 0);
_callback = context[callback];
}
if (!_callback) {
throw 'no callback function exists for "' + callback + '"';
}
callback = function() {
return _callback.apply(context, noArg ? [] : arguments);
};
}
// check for special wrapper function
var match = event.match(specialWrapper);
if (match) {
var specialMethodName = match[1],
args = match[2].split(/\s*,\s*/),
rest = match[3],
specialHandler = React.events.specials[specialMethodName];
if (specialHandler) {
if (args.length === 1 && args[0] === '') {
args = [];
}
callback = specialHandler.call(context, callback, args);
return createHandler(rest, callback, context, true);
} else {
throw new Error('invalid special event handler "' + specialMethodName + "'");
}
}
var parts = event.match(splitter),
handlerName = parts[1];
path = parts[2],
handler = handlers[handlerName];
// check pattern handlers if no match
for (var i = 0; !handler && i < patternHandlers.length; i++) {
if (handlerName.match(patternHandlers[i].pattern)) {
handler = patternHandlers[i].handler;
}
}
if (!handler) {
throw 'no handler registered for "' + event + '"';
}
return handler.call(context, {
key: handlerName,
path: path
}, callback);
}
// predefined templates of common handler types for simpler custom handling
var handlerTemplates = {
/**
* Return a handler which will use a standard format of on(eventName, handlerFunction) and off(eventName, handlerFunction)
* @param data {object} handler options
* - target {object or function()}: the target to bind to or function(name, event) which returns this target ("this" is the React component)
* - onKey {string}: the function attribute used to add the event binding (default is "on")
* - offKey {string}: the function attribute used to add the event binding (default is "off")
*/
standard: function(data) {
var accessors = {
on: data.onKey || 'on',
off: data.offKey || 'off'
},
target = data.target;
return function(options, callback) {
var path = options.path;
function checkTarget(type, context) {
return function() {
var _target = (typeof target === 'function') ? target.call(context, path) : target;
if (_target) {
// register the handler
_target[accessors[type]](path, callback);
}
};
}
return {
on: checkTarget('on', this),
off: checkTarget('off', this),
initialize: data.initialize
};
};
}
};
var eventManager = React.events = {
// placeholder for special methods
specials: {},
/**
* Register an event handler
* @param identifier {string} the event type (first part of event definition)
* @param handlerOrOptions {function(options, callback) *OR* options object}
*
* handlerOrOptions as function(options, callback) a function which returns the object used as the event handler.
* @param options {object}: will contain a *path* attribute - the event key (without the handler key prefix).
* if the custom handler was registered as "foo" and events hash was { "foo:abc": "..." }, the path is "abc"
* @param callback {function}: the callback function to be bound to the event
*
* handlerOrOptions as options: will use a predefined "standard" handler; this assumes the event format of "{handler identifier}:{target identifier}:{event name}"
* @param target {object or function(targetIdentifier, eventName)} the target to bind/unbind from or the functions which retuns this target
* @param onKey {string} the attribute which identifies the event binding function on the target (default is "on")
* @param offKey {string} the attribute which identifies the event un-binding function on the target (default is "off")
*/
handle: function(identifier, optionsOrHandler) {
if (typeof optionsOrHandler !== 'function') {
// it's options
optionsOrHandler = handlerTemplates[optionsOrHandler.type || 'standard'](optionsOrHandler);
}
if (identifier instanceof RegExp) {
patternHandlers.push({
pattern: identifier,
handler: optionsOrHandler
});
} else {
handlers[identifier] = optionsOrHandler;
}
}
};
//// REGISTER THE DEFAULT EVENT HANDLERS
if (typeof window != 'undefined') {
/**
* Bind to window events
* format: "window:{event name}"
* example: events: { 'window:scroll': 'onScroll' }
*/
eventManager.handle('window', {
target: window,
onKey: 'addEventListener',
offKey: 'removeEventListener'
});
}
var objectHandlers = {
/**
* Bind to events on components that are given a [ref](http://facebook.github.io/react/docs/more-about-refs.html)
* format: "ref:{ref name}:{event name}"
* example: "ref:myComponent:something-happened": "onSomethingHappened"
*/
ref: function(refKey) {
return this.refs[refKey];
},
/**
* Bind to events on components that are provided as property values
* format: "prop:{prop name}:{event name}"
* example: "prop:componentProp:something-happened": "onSomethingHappened"
*/
prop: function(propKey) {
return this.props[propKey];
}
};
function registerObjectHandler(key, objectFactory) {
eventManager.handle(key, function(options, callback) {
var parts = options.path.match(splitter),
objectKey = parts[1],
ev = parts[2],
bound, componentState;
return {
on: function() {
var target = objectFactory.call(this, objectKey);
if (target) {
componentState = target.state || target;
target.on(ev, callback);
bound = target;
}
},
off: function() {
if (bound) {
bound.off(ev, callback);
bound = undefined;
componentState = undefined;
}
},
isStale: function() {
if (bound) {
var target = objectFactory.call(this, objectKey);
if (!target || (target.state || target) !== componentState) {
// if the target doesn't exist now and we were bound before or the target state has changed we are stale
return true;
}
} else {
// if we weren't bound before but the component exists now, we are stale
return !!target;
}
}
};
});
}
var objectFactory;
for (var key in objectHandlers) {
registerObjectHandler(key, objectHandlers[key]);
}
/**
* Allow binding to setInterval events
* format: "repeat:{milis}"
* example: events: { 'repeat:3000': 'onRepeat3Sec' }
*/
eventManager.handle('repeat', function(options, callback) {
var delay = parseInt(options.path, 10),
id;
return {
on: function() {
id = setInterval(callback, delay);
},
off: function() {
id = !!clearInterval(id);
}
};
});
/**
* Like setInterval events *but* will only fire when the user is actively viewing the web page
* format: "!repeat:{milis}"
* example: events: { '!repeat:3000': 'onRepeat3Sec' }
*/
eventManager.handle('!repeat', function(options, callback) {
var delay = parseInt(options.path, 10),
keepGoing;
function doInterval(suppressCallback) {
if (suppressCallback !== true) {
callback();
}
setTimeout(function() {
if (keepGoing) {
requestAnimationFrame(doInterval);
}
}, delay);
}
return {
on: function() {
keepGoing = true;
doInterval(true);
},
off: function() {
keepGoing = false;
}
};
});
//// REGISTER THE REACT MIXIN
React.mixins.add('events', function() {
var rtn = [{
/**
* Return a callback fundtion that will trigger an event on "this" when executed with the provided parameters
*/
triggerWith: function(eventName) {
var args = Array.prototype.slice.call(arguments),
self = this;
return function() {
self.trigger.apply(this, args);
};
},
getInitialState: function() {
var handlers = [];
if (this.events) {
var events = normalizeEvents(this.events);
var handler;
for (var ev in events) {
handler = createHandler(ev, events[ev], this);
if (handler.initialize) {
handler.initialize.call(this);
}
handlers.push(handler);