[英]Simulate C# like events in javascript
I want to simulate C#'s events in JavaScript: what i want to do is something like this: 我想在JavaScript中模拟C#的事件:我想要做的是这样的事情:
Let's say i have the following code: 假设我有以下代码:
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();
What i want to do is when i call my_class_obj.Event, all the subscribed functions get called. 我想要做的是当我调用my_class_obj.Event时,所有订阅的函数都被调用。
Could this be achieved purely in JavaScript or i need to find my way around through DOM events? 这可以纯粹用JavaScript实现,还是需要通过DOM事件找到方法?
How about writing a separate event class: Reference link: http://alexatnet.com/articles/model-view-controller-mvc-javascript 如何编写单独的事件类:参考链接: 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);
}
}
};
And your my class. 而你的我的班级。 For example:
例如:
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);
}
}
Subscribe to event example code: 订阅活动示例代码:
var my_class_obj = new MyClass("Test");
my_class_obj.nameChanged.attach(function (sender,args){
});
my_class_obj.setName("newName");
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.
您还可以根据需要添加更多事件:例如addressChanged事件。 This approach also simulate c# event (sender and args)
这种方法也模拟了c#事件(发送者和args)
You could write your own Observer (publisher-subscriber) read the GOF. 您可以编写自己的观察者(发布者 - 订阅者)阅读GOF。 Or, if using jQuery, custom events ( http://api.jquery.com/trigger/ ) can help you out.
或者,如果使用jQuery,自定义事件( http://api.jquery.com/trigger/ )可以帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.