如何在Win8Metro应用程序的Javascript代码中捕获自己的C#事件

How to catch own C# events in Javascript code in Win8 Metro apps?

本文关键字:自己的 事件 代码 Javascript Win8Metro 应用程序      更新时间:2023-09-26

我在谷歌上找到了如何在Javascript代码中实现C#事件的事件侦听器的例子,但不知怎么的,在我的情况下,似乎什么都不起作用。

我的C#类:

namespace Engine
{
    public delegate void EventDelegate();
    public sealed class MyClass;
    {
        public event EventDelegate nowEvent;
        public void runJobs()
        {
           if (nowEvent == null)
           {
             Debug.WriteLine("What? Nobody subscribed???");
           }
        }
    }
}

Javascript端:

WinJS.Namespace.define("App", {
    myclass: new Engine.MyClass()
});
App.myclass.addEventListener("nowEvent", function onReady() {
            console.error("hello");
        });
App.myclass.runJobs();

将onReady函数附加到nowEvent事件并运行runJobs()后,MyClass.nowEvent为null。

在JS中订阅自己类的C#事件的工作语法是什么。有什么想法吗?

编辑:甘比特建议后:

App.myclass.addEventListener("nowevent", function onReady() {
                console.error("hello");
            });

事件指针不再为空,但当我触发事件时,我得到:

Engine.winmd 中首次出现类型为"System.InvalidCastException"的异常

您可能会遇到投影更改所用语言名称大小写的方式。对于Javascript,事件的约定是小写的。因此,在C#中,您将事件定义为"nowEvent",在Javascript中,您称其为"nowEvent"。

App.myclass.addEventListener("nowevent", function onReady() {
        console.error("hello");
    });

您可以使用WinJS.Application.queueEvent("myEvent")函数。然后,您可以通过WinJS.Application.addEventListener("myEevent",function(){}); 将事件侦听器添加到WinJS.Application

您还可以使用WinJS.Utilities eventMixin将事件添加到类中。

WinJS.Class.mix(EventObject, eventMixin);

然后,您可以在应用了mixin的类上使用addEventListener、removeEventListener等。