听在角控制器文档事件 [英] Listen document event in angular controller
问题描述
如何角的控制器赶上事件?
How to catch event in angular's controller?
我的文档级事件,所以我需要赶上事件的角度控制器,这可能吗?
I have document level events, so I need to catch event in angular controller, is it possible?
更新
我有独立的js与相机的一些行动处理文件。
I have standalone js file with handling of some actions from camera.
document.addEventListener('myCameraEvent', handleMyCameraEvent);
和我想触发角控制器或指令此事件。谁能解释一下,怎么可能用角来实现?
And I want to trigger this event in angular controller or directive. Could anyone explain, how is it possible to implement with angular?
推荐答案
下面是一个普通的自定义事件的观察者服务:
Here's a generic custom events observer service:
.service('Camera', function($document) {
//map of current subscribers
var subscribers = {};
//notifies all subscribers of particular event type
function notify(event) {
var handlers = subscribers[event.type] || [];
for (var i = 0; i < handlers.length; i++) {
handlers(i)(event);
}
}
//adds new handler to subscribers list
//returns object with unsubscribe() method
this.subscribe(eventType, handler) {
var handlers = subscribers[eventType] || [];
handlers.push(handler);
return (function(type, index) {
return {
unsubscribe: function() {
subscribers[type].splice(index);
}
}
})(eventType, handlers.length - 1);
}
//register custom events
$document.on('myCameraEvent', function(event) {
notify(event);
});
$document.on('myOtherCameraEvent', function(event) {
notify(event);
});
});
在你的控制器,你会使用这样的:
In your controller, you'd use it like this:
.controller('MyCtrl', function($scope, Camera) {
subscriber = Camera.subscribe('myCustomEvent', customEventHandler);
function customEventHandler(event) {
//process event
//..
//if handler is not needed anymore, unsubscribe
//subscriber.unsubscribe();
}
})
当然,这只是一般的想法。你可能想在摄像机的服务,例如 Camera.onSnapshot(snapshothandler)具体方法; Camera.onTurnOff(turnOffHandler);
将登记处理特定事件抽象掉的事件名称
Of course, this is just general idea. You'd might want to have specific methods on Camera service, for example Camera.onSnapshot(snapshothandler); Camera.onTurnOff(turnOffHandler);
which would register handlers to specific events to abstract away the event names.
这篇关于听在角控制器文档事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!