locked
Event handlers context (v7) RRS feed

  • Question

  • I'm also getting trouble with event handlers context because unlike 6.3, "this" in event handlers
    is now the event itself (which is not only a redondant, but also prevents accessing the instance
    in which the function is defined).



    For example:

    function ExampleClass(){}


    // Event handler
    ExampleClass.prototype.onclick = function(e){
        console.log(this);
        console.log('Hello= ' + this.hello);
    };


    // Create two different instances of the Test object
    var obj1 = new ExampleClass();
    obj1.hello = 123;

    var obj2 = new ExampleClass();
    obj2.hello = 234;


    // In this case, "this" is the Test instance
    obj1.onclick(null);
    obj2.onclick(null);


    // In this case, "this" is the event (same value as "e")
    // therefore it cannot access the property "hello" of the instance.
    Microsoft.Maps.Events.addHandler(map, 'click', obj1.onclick);
    Microsoft.Maps.Events.addHandler(map, 'click', obj2.onclick);




    The event handler cannot access "hello" because it has no reference to the matching ExampleClass object, so how can the callback function possibly access instance properties from the event handler ?
    • Edited by wildpeaks Monday, November 22, 2010 11:30 AM
    Monday, November 22, 2010 10:22 AM

Answers

  • How about wrapping your class and doing something like this:

     

    var ExampleClass = function(param){
    	var p = param;
    	
    	return function(e){
    		alert("Hello " + p);
    	};
    };
    
    var obj1 = new ExampleClass("Ricky");
    var obj2 = new ExampleClass("Bob");
    
    Microsoft.Maps.Events.addHandler(map, 'click', obj1);
    Microsoft.Maps.Events.addHandler(map, 'click', obj2);
    
    


    Windows Live Developer MVP - http://rbrundritt.spaces.live.com | http://inknowledge.co.uk
    Monday, November 22, 2010 2:24 PM
    Moderator

All replies

  • For 7.1, I would suggest adding a 4th parameter to "Microsoft.Maps.Events.addHandler " that allows passing additional parameters to the event handler.
    Monday, November 22, 2010 10:40 AM
  • How about wrapping your class and doing something like this:

     

    var ExampleClass = function(param){
    	var p = param;
    	
    	return function(e){
    		alert("Hello " + p);
    	};
    };
    
    var obj1 = new ExampleClass("Ricky");
    var obj2 = new ExampleClass("Bob");
    
    Microsoft.Maps.Events.addHandler(map, 'click', obj1);
    Microsoft.Maps.Events.addHandler(map, 'click', obj2);
    
    


    Windows Live Developer MVP - http://rbrundritt.spaces.live.com | http://inknowledge.co.uk
    Monday, November 22, 2010 2:24 PM
    Moderator