Udostępnij za pośrednictwem


Handling Windows Runtime events in JavaScript

This documentation is archived and is not being maintained.

Windows Runtime events are not represented in the same way in JavaScript as they are in C++ or the .NET Framework. They are not class properties, but rather are represented as (lowercase) string identifiers that are passed to the class's addEventListener and removeEventListener methods. For example, you can add an event handler for the Geolocator.PositionChanged event by passing the string positionchanged to the Geolocator.addEventListener method:

var locator = new Windows.Devices.Geolocation.Geolocator();
locator.addEventListener(
    "positionchanged",
    function (ev) {
        console.log("Got event");
    });

You can also set the locator.onpositionchanged property:

locator.onpositionchanged =
    function (ev) {
        console.log("Got event");
    };

Another difference between .NET/C++ and JavaScript is the number of parameters taken by an event handler. In .NET/C++, a handler takes two: the event sender, and the event data. In JavaScript, the two are bundled as a single Event object. In the following example, the ev parameter contains both the sender of the event (the target property) and the event data properties (here, just position). The event data properties are the ones that are documented for each event.

function (ev) {
    console.log("Sender: " + ev.target);
    console.log("Position: " +
        ev.position.latitude + "," +
        ev.position.longitude);
};

Important

Windows Runtime features are not available for apps that run in Internet Explorer.

See also

Using the Windows Runtime in JavaScript