How to register event handlers for TypeScript declarations

Topics: General
Aug 10, 2013 at 12:37 PM
Ok this might be a silly question but I've been using TypeScript declarations, for example the Bing Maps one (https://bingmapsts.codeplex.com/) and I can't figure out how to hook to events.

On the Map class (in Microsoft.Maps.d.ts) there are a couple of events declared:
viewchange: () => any;
viewchangeend: () => any;
viewchangestart: () => any;
And I've tried hooking a function like the following inside a typescript file without success:
///<reference path="Bing/Microsoft.Maps.All.d.ts" />

window.onload = function()
{
    var map = new Microsoft.Maps.Map(document.getElementById('map'),
        {
            backgroundColor: 0,
            click: () => alert('click'),
            viewchangestart: () => alert('viewchangestart'),                    
        });
}
Hopefully someone can tell me what I'm doing wrong here.

Thanks
Guy
Aug 14, 2013 at 3:19 PM
Looks like your syntax maybe slightly out.

the format for a function in TypeScript is like this:
() => { alert('test') }
So possibly your code should read :
///<reference path="Bing/Microsoft.Maps.All.d.ts" />

window.onload = function () 
{
    var map = new Microsoft.Maps.Map(document.getElementById('map'),
        {
            backgroundColor: 0,
            click: () =>  { alert('click'); },
            viewchangestart: () => { alert('viewchangestart'); }                    
        });
}
Aug 14, 2013 at 8:52 PM
Lambdas can be expressed with or without brackets: both ways produce the same valid javascript output FYI.

Turns out the declaration is wrong and shouldn't have those events declared in the Map class. The proper way to register event handlers with Bing Maps is to use the Microsoft.Maps.Event.addHandler function. Adding the following declaration file is the proper way to do it:
declare module Microsoft.Maps.Events
{
    function addHandler(map: Microsoft.Maps.Map, event: string, func: Function);
}
And using it this way:
Microsoft.Maps.Events.addHandler(map, 'viewchangestart', () => alert('viewchangestart'));