|
| 1 | +import { Rx, hasRx, isSubject, warn, getKey, unsub } from '../util' |
| 2 | + |
| 3 | +export default { |
| 4 | + // Example ./example/counter_dir.html |
| 5 | + bind (el, binding, vnode) { |
| 6 | + if (!hasRx()) { |
| 7 | + return |
| 8 | + } |
| 9 | + |
| 10 | + let handle = binding.value |
| 11 | + const event = binding.arg |
| 12 | + const streamName = binding.expression |
| 13 | + |
| 14 | + if (isSubject(handle)) { |
| 15 | + handle = { subject: handle } |
| 16 | + } else if (!handle || !isSubject(handle.subject)) { |
| 17 | + warn( |
| 18 | + 'Invalid Subject found in directive with key "' + streamName + '".' + |
| 19 | + streamName + ' should be an instance of Rx.Subject or have the ' + |
| 20 | + 'type { subject: Rx.Subject, data: any }.', |
| 21 | + vnode.context |
| 22 | + ) |
| 23 | + return |
| 24 | + } |
| 25 | + |
| 26 | + const subject = handle.subject |
| 27 | + const next = (subject.next || subject.onNext).bind(subject) |
| 28 | + handle.subscription = Rx.Observable.fromEvent(el, event).subscribe(e => { |
| 29 | + next({ |
| 30 | + event: e, |
| 31 | + data: handle.data |
| 32 | + }) |
| 33 | + }) |
| 34 | + |
| 35 | + // store handle on element with a unique key for identifying |
| 36 | + // multiple v-stream directives on the same node |
| 37 | + ;(el._rxHandles || (el._rxHandles = {}))[getKey(binding)] = handle |
| 38 | + }, |
| 39 | + |
| 40 | + update (el, binding) { |
| 41 | + const handle = binding.value |
| 42 | + const _handle = el._rxHandles && el._rxHandles[getKey(binding)] |
| 43 | + if (_handle && handle && isSubject(handle.subject)) { |
| 44 | + _handle.data = handle.data |
| 45 | + } |
| 46 | + }, |
| 47 | + |
| 48 | + unbind (el, binding) { |
| 49 | + const key = getKey(binding) |
| 50 | + const handle = el._rxHandles && el._rxHandles[key] |
| 51 | + if (handle) { |
| 52 | + unsub(handle.subscription) |
| 53 | + el._rxHandles[key] = null |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments