[英]How to convert custom library events (ie. Google Maps events) into Observable stream in RxJS?
I want to create an RxJS observable stream from Google Map events. 我想从Google Map事件中创建一个RxJS可观察流。 I know how to do this from native browser events, like so:
我知道如何从本机浏览器事件中执行此操作,如下所示:
var result = document.getElementById('result');
var source = Rx.Observable.fromEvent(document, 'mousemove');
var subscription = source.subscribe(function (e) {
result.innerHTML = e.clientX + ', ' + e.clientY;
});
The mousemove
is a browser event, which leads me to believe that .fromEvent()
recognizes mousemove
as a hard-coded default. mousemove
是一个浏览器事件,这使我相信.fromEvent()
将mousemove
识别为硬编码默认值。 However, if I want to recognize custom events how can I create an observable stream? 但是,如果我想识别自定义事件,我该如何创建可观察的流? Take for example Google Maps:
以Google地图为例:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363, lng: 131.044}
});
map.addListener('center_changed', function() {
var center = map.getCenter()
console.log(center)
});
The reason why I want to convert these google map events into an observable stream is so that I can use RxJS debounce
for performance improvements. 我想将这些谷歌地图事件转换为可观察流的原因是我可以使用RxJS
debounce
来提高性能。 That way center_changed
is only recognized in batches (instead of firing 10x over 2 seconds, it just recognizes the last 1x in that same 2 seconds). 这样,
center_changed
只能批量识别(而不是在2秒内发射10倍,它只识别同一个2秒内的最后1x)。 My dilemma is converting that custom Google Maps event into an observable stream. 我的困境是将自定义Google Maps事件转换为可观察的流。 Perhaps there is an easy way to continuously add to an observable, but from my search I have not found out how to do that.
也许有一种简单的方法可以不断添加到一个可观察的,但从我的搜索中我还没有发现如何做到这一点。
I really appreciate your help in this matter! 我真的很感谢你在这件事上的帮助!
You should be able to use fromEventPattern
to do what you want: 您应该能够使用
fromEventPattern
来执行您想要的操作:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: { lat: -25.363, lng: 131.044 }
});
var source = Rx.Observable.fromEventPattern(
function (handler) {
return map.addListener('center_changed', handler);
},
function (handler, listener) {
google.maps.event.removeListener(listener);
}
);
source.subscribe(function () {
console.log(map.getCenter());
});
fromEventPattern
lets you provide the add and remove implementations, so it's easy to get an observable from most types of 'custom' event mechanisms. fromEventPattern
允许您提供添加和删除实现,因此很容易从大多数类型的“自定义”事件机制中获得可观察的。 Note that the value returned by the add handler is passed to the remove handler as the second parameter. 请注意,add处理程序返回的值作为第二个参数传递给remove处理程序。 In this case, it's the listener - which is what's needed when removing Google Maps event listeners.
在这种情况下,它是听众 - 这是移除Google Maps事件监听器时所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.