Skip to content

New feature: $createObservableFunction #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,36 @@ var vm = new Vue({
})
```

#### `$createObservableMethod(methodName)`

> This feature requires RxJS.

Convert function calls to observable sequence which emits the call arguments.

This is a prototype method added to instances. Use it to create a shared hot observable from a function name. The function will assigned as a vm method.

```html
<custom-form :onSubmit="submitHandler"></custom-form>
```
``` js
var vm = new Vue({
subscriptions () {
return {
// requires `share` operator
formData: this.$createObservableMethod('submitHandler')
}
}
})
```
Or, use the `observableMethods` convenience option:
``` js
new Vue({
observableMethods: { submitHandler:'submitHandler$' }
})
```
[example](https://github.com/vuejs/vue-rx/blob/master/example/counter-function.html)


### Caveats

You cannot use the `watch` option to watch subscriptions, because it is processed before the subscriptions are set up. But you can use `$watch` in the `created` hook instead.
Expand Down
47 changes: 47 additions & 0 deletions example/counter-function.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!-- this demo requires a browser that natively supports ES2015 -->

<script src="https://unpkg.com/@reactivex/rxjs/dist/global/Rx.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="../dist/vue-rx.js"></script>

<div id="app">
<div>{{ count }}</div>

<!-- callback declared on observableMethods -->
<button v-on:click="muchMore(500)">Add 500</button>

<button v-on:click="minus(minusDelta1)"> Minus on Click </button>

<pre>{{ $data }}</pre>

</div>

<script>
new Vue({
el: '#app',

data () {
return {
minusDelta1: -1,
minusDelta2: -1
}
},

// declare callback Subjects
observableMethods: { muchMore:'muchMore$', minus:'minus$'}, // ['muchMore','minus'] as equal

subscriptions () {
var count$ = Rx.Observable
.merge(
this.muchMore$,
this.minus$
)
.startWith(0)
.scan((total, change) => total + change)

return {
count: count$
}
}
})
</script>
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vue-rx",
"version": "3.2.0",
"version": "3.3.0",
"description": "RxJS bindings for Vue",
"main": "dist/vue-rx.js",
"files": [
Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import watchAsObservable from './methods/watchAsObservable'
import fromDOMEvent from './methods/fromDOMEvent'
import subscribeTo from './methods/subscribeTo'
import eventToObservable from './methods/eventToObservable'
import createObservableMethod from './methods/createObservableMethod'

export default function VueRx (Vue, Rx) {
install(Vue, Rx)
Expand All @@ -16,6 +17,7 @@ export default function VueRx (Vue, Rx) {
Vue.prototype.$fromDOMEvent = fromDOMEvent
Vue.prototype.$subscribeTo = subscribeTo
Vue.prototype.$eventToObservable = eventToObservable
Vue.prototype.$createObservableMethod = createObservableMethod
}

// auto install
Expand Down
56 changes: 56 additions & 0 deletions src/methods/createObservableMethod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Rx, hasRx, warn } from '../util'

/**
* @name Vue.prototype.$createObservableMethod
* @description Creates an observable from a given function name.
* @param {String} methodName Function name
* @param {Boolean} [passContext] Append the call context at the end of emit data?
* @return {Observable} Hot stream
*/
export default function createObservableMethod (methodName, passContext) {
if (!hasRx()) {
return
}
const vm = this

if (!Rx.Observable.prototype.share) {
warn(
`No 'share' operator. ` +
`$createObservableMethod returns a shared hot observable. ` +
`Try import 'rxjs/add/operator/share' for creating ${methodName}`,
vm
)
return
}

if (vm[methodName] !== undefined) {
warn(
'Potential bug: ' +
`Method ${methodName} already defined on vm and has been overwritten by $createObservableMethod.` +
String(vm[methodName]),
vm
)
}

const creator = function (observer) {
vm[methodName] = function () {
const args = Array.from(arguments)
if (passContext) {
args.push(this)
observer.next(args)
} else {
if (args.length <= 1) {
observer.next(args[0])
} else {
observer.next(args)
}
}
}
return function () {
delete vm[methodName]
}
}

// Must be a hot stream otherwise function context may overwrite over and over again
return Rx.Observable.create(creator).share()
}
13 changes: 13 additions & 0 deletions src/mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ export default {
}
}

const observableMethods = vm.$options.observableMethods
if (observableMethods) {
if (Array.isArray(observableMethods)) {
observableMethods.forEach(methodName => {
vm[ methodName + '$' ] = vm.$createObservableMethod(methodName)
})
} else {
Object.keys(observableMethods).forEach(methodName => {
vm[observableMethods[methodName]] = vm.$createObservableMethod(methodName)
})
}
}

let obs = vm.$options.subscriptions
if (typeof obs === 'function') {
obs = obs.call(vm)
Expand Down
67 changes: 67 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const Observable = require('rxjs/Observable').Observable
const Subject = require('rxjs/Subject').Subject
const Subscription = require('rxjs/Subscription').Subscription
require('rxjs/add/observable/fromEvent')
require('rxjs/add/operator/share')

// user
require('rxjs/add/operator/map')
Expand Down Expand Up @@ -316,3 +317,69 @@ test('$eventToObservable() with lifecycle hooks', done => {
vm.$destroy()
})
})

test('$createObservableMethod() with no context', done => {
const vm = new Vue({
created () {
this.$createObservableMethod('add')
.subscribe(function (param) {
expect(param).toEqual('hola')
done(param)
})
}
})
nextTick(() => {
vm.add('hola')
})
})

test('$createObservableMethod() with muli params & context', done => {
const vm = new Vue({
created () {
this.$createObservableMethod('add', true)
.subscribe(function (param) {
expect(param[0]).toEqual('hola')
expect(param[1]).toEqual('mundo')
expect(param[2]).toEqual(vm)
done(param)
})
}
})
nextTick(() => {
vm.add('hola', 'mundo')
})
})

test('observableMethods mixin', done => {
const vm = new Vue({
observableMethods: ['add'],
created () {
this.add$
.subscribe(function (param) {
expect(param[0]).toEqual('Qué')
expect(param[1]).toEqual('tal')
done(param)
})
}
})
nextTick(() => {
vm.add('Qué', 'tal')
})
})

test('observableMethods mixin', done => {
const vm = new Vue({
observableMethods: { 'add': 'plus$' },
created () {
this.plus$
.subscribe(function (param) {
expect(param[0]).toEqual('Qué')
expect(param[1]).toEqual('tal')
done(param)
})
}
})
nextTick(() => {
vm.add('Qué', 'tal')
})
})