您能告诉我如何将其翻译为TypeScript
吗?
使用SharpKit.JavaScript;
namespace MyNamespace
{
[JsType(JsMode.Prototype)]
public class JsEventArgs
{
}
public delegate void JsEventHandler<in T>(object sender, T args) where T : JsEventArgs;
public delegate void JsEventHandler(object sender, JsEventArgs args);
}
在其他课程中使用:
public event JsEventHandler<LayerVisivilityEventArgs> Changed;
我试过了:
module JsEvent {
export class JsEventArgs {
}
public JsEventHandler: (sender: Object, args: any) => void;
public JsEventHandler: (sender: Object, args: JsEventArgs) => void;
}
答案 0 :(得分:6)
我编写了一个类似于.NET Delegate类的小类(它是为.NET中的事件隐式创建的)
export interface IDelegate {
(sender: any, ...parameters: any[]): void;
}
export class DelegateBuilder {
private callees: IDelegate[];
constructor() {
this.callees = [];
}
invoke(sender: any, ...parameters: any[]) {
for (var i = 0; i < this.callees.length; i++) {
var callee = this.callees[i];
if (caller)
callee(sender, parameters);
}
}
contains(callee: IDelegate) : bool {
if (!callee)
return false;
return this.callees.indexOf(callee) >= 0;
}
add(callee: IDelegate): DelegateBuilder {
if (!callee)
return this;
if (!this.contains(callee))
this.callees.push(callee);
return this;
}
remove(callee: IDelegate): DelegateBuilder {
if (!callee)
return this;
var index = this.callees.indexOf(callee);
if (index >= 0)
this.callees.splice(index, 1);
return this;
}
toDelegate() : IDelegate {
return (sender: any, ...parameters: any[]) => this.invoke(sender, parameters);
}
}
答案 1 :(得分:4)
我认为你需要停止在C#中思考,并开始在TypeScript中思考。
此代码:
module JsEvent {
export class JsEventArgs {
}
public JsEventHandler: (sender: Object, args: any) => void;
public JsEventHandler: (sender: Object, args: JsEventArgs) => void;
}
...尝试向模块添加两个属性,但只允许在类(或接口)上使用属性。
TypeScript并不真正使用委托 - 您可以连接一个事件(例如,在JQuery中),如下所示:
$('selector').click((e:JQueryEventObject) => {
// Do something here.
});
......或者,避免使用JQuery:
var div: HTMLDivElement = new HTMLDivElement();
div.onclick = (e: MouseEvent) => {
// Do something here.
};
......或者,没有匿名函数:
div.onclick = doSomething;
function doSomething(e:MouseEvent):void{
// Do something here.
}
我认为你最接近代表的模式是这样的(来自http://forum.unity3d.com/threads/9679-Javascript-Delegates!):
module JSEvents {
class JSEventClass {
public delegate:(e:string) => any;
constructor() => {
this.delegate = this.doSomething;
this.delegate("Hello, Delegate World");
}
public doSomething(e: string): any {
console.log("Doing Something: " + e);
}
}
}
...但是在TypeScript / JavaScript世界中,我没有看到这种模式直接调用doSomething()
所取得的成就。
答案 2 :(得分:0)
我认为这是对相关代码的密切翻译。但是,这并未涉及another answer已涵盖的事件处理。
module MyNamespace
{
export class JsEventArgs
{
}
export interface JsEventHandler<T extends JsEventArgs> {
(sender: any, args: T): void;
}
export interface JsEventHandler {
(sender: any, args: JsEventArgs): void;
}
}