是否可以向JavaScript函数/类添加事件处理程序?
我正在尝试注册JavaScript函数/类上的事件,并试图使其尽可能接近下面的C#类。这有可能吗 C# JS是否可以向JavaScript函数/类添加事件处理程序?,javascript,oop,events,Javascript,Oop,Events,我正在尝试注册JavaScript函数/类上的事件,并试图使其尽可能接近下面的C#类。这有可能吗 C# JS 这是完全可能的,您可以研究许多处理事件的库中的一个来检查它们的实现 下面是一个非常简单的草案,它不处理未侦听、事件类型、参数、作用域、冒泡等: function EventHandler(target) { var listeners = []; this.add = function(handler) { listeners.push(handler); };
这是完全可能的,您可以研究许多处理事件的库中的一个来检查它们的实现 下面是一个非常简单的草案,它不处理未侦听、事件类型、参数、作用域、冒泡等:
function EventHandler(target) {
var listeners = [];
this.add = function(handler) {
listeners.push(handler);
};
this.fire = function() {
for (var i=0; i<listeners.length; i++) {
listeners[i].call(target);
}
};
}
function MyClass()
{
this.name = 'myclass';
// Add a private event handler...
var eventHandler = new EventHandler(this);
this.listen = function(f) {
eventHandler.add(f);
};
this.raiseEvent = function(){
eventHandler.fire();
};
}
var mc = new MyClass();
mc.listen(function(){ console.log(this.name); });
mc.raiseEvent();
函数事件处理程序(目标){
var侦听器=[];
this.add=函数(处理程序){
push(handler);
};
this.fire=函数(){
对于(var i=0;iYou可以考虑使用服务器推送实现类似的功能,请看这看起来很完美!谢谢
function MyClass()
{
// Add an event handler...
this.raiseEvent = function(){
// raise the event
}
}
var mc = new MyClass();
//register for the event
function EventHandler(target) {
var listeners = [];
this.add = function(handler) {
listeners.push(handler);
};
this.fire = function() {
for (var i=0; i<listeners.length; i++) {
listeners[i].call(target);
}
};
}
function MyClass()
{
this.name = 'myclass';
// Add a private event handler...
var eventHandler = new EventHandler(this);
this.listen = function(f) {
eventHandler.add(f);
};
this.raiseEvent = function(){
eventHandler.fire();
};
}
var mc = new MyClass();
mc.listen(function(){ console.log(this.name); });
mc.raiseEvent();