在javascript中模拟类似C#的事件 [英] Simulate C# like events in javascript

查看:95
本文介绍了在javascript中模拟类似C#的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中模拟C#的事件:我想要做的是这样的事情:

I want to simulate C#'s events in JavaScript: what i want to do is something like this:

假设我有以下代码:

function addToInvocationList(method, listener) {
      *Some code to add listener to the invocation list of method*
}

function MyClass() {
}

MyClass.prototype.Event = function() {}

var my_class_obj = new MyClass();

function subscriberFunction1() {}
function subscriberFunction2() {}
function subscriberFunction3() {}

addToInvocationList(my_class_obj.Event, subscriberFunction1);
addToInvocationList(my_class_obj.Event, subscriberFunction2);
addToInvocationList(my_class_obj.Event, subscriberFunction3);

my_class_obj.Event();

我想做的是当我调用my_class_obj.Event时,所有订阅的函数都被调用。

What i want to do is when i call my_class_obj.Event, all the subscribed functions get called.

这可以纯粹用JavaScript实现,还是需要通过DOM事件找到答案?

Could this be achieved purely in JavaScript or i need to find my way around through DOM events?

推荐答案

如何编写单独的事件类:参考链接: http://alexatnet.com/articles/model-view-controller-mvc-javascript

How about writing a separate event class: Reference link: http://alexatnet.com/articles/model-view-controller-mvc-javascript

function Event(sender) {
    this._sender = sender;
    this._listeners = [];
}

Event.prototype = {
    attach: function (listener) {
        this._listeners.push(listener);
    },
    notify: function (args) {
        for (var i = 0; i < this._listeners.length; i++) {
            this._listeners[i](this._sender, args);
        }
    }
};

还有我的班级。例如:

function MyClass(name) {
     var self = this;
     self.Name = name;
     self.nameChanged = new Event(this);

     self.setName = function (newName){
         self.Name = newName;
         self.nameChanged.notify(newName);
     }
}

订阅活动示例代码:

var my_class_obj = new MyClass("Test");
my_class_obj.nameChanged.attach(function (sender,args){

});
my_class_obj.setName("newName");

您可以附加更多事件处理程序,并且将调用所有这些事件处理程序。您还可以根据需要添加更多事件:例如addressChanged事件。这种方法也模拟c#事件(发送者和args)

You can attach more event handlers and all these event handlers will get called. And you can also add more events as you'd like: addressChanged event for example. This approach also simulate c# event (sender and args)

这篇关于在javascript中模拟类似C#的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆