UNPKG

1.74 kBPlain TextView Raw
1import { bindingMode, EventSubscriber, bindingBehavior } from 'aurelia-binding';
2
3// tslint:disable-next-line:max-line-length
4const eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">';
5const notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way/ from-view bindings on input/select elements.';
6
7@bindingBehavior('updateTrigger')
8export class UpdateTriggerBindingBehavior {
9
10 bind(binding, source, ...events) {
11 if (events.length === 0) {
12 throw new Error(eventNamesRequired);
13 }
14 if (binding.mode !== bindingMode.twoWay && binding.mode !== bindingMode.fromView) {
15 throw new Error(notApplicableMessage);
16 }
17
18 // ensure the binding's target observer has been set.
19 let targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty);
20 if (!targetObserver.handler) {
21 throw new Error(notApplicableMessage);
22 }
23 binding.targetObserver = targetObserver;
24
25 // stash the original element subscribe function.
26 targetObserver.originalHandler = binding.targetObserver.handler;
27
28 // replace the element subscribe function with one that uses the correct events.
29 let handler = new EventSubscriber(events);
30 targetObserver.handler = handler;
31 }
32
33 // eslint-disable-next-line @typescript-eslint/no-unused-vars
34 unbind(binding, source) {
35 let targetObserver = binding.targetObserver;
36 // restore the state of the binding.
37 targetObserver.handler.dispose();
38 targetObserver.handler = targetObserver.originalHandler;
39 targetObserver.originalHandler = null;
40 }
41}