1

I'm defining a jquery ui-grid component in my controller, the minified example of which is shown below:

class myController {
    constructor($scope) {        

        this.$scope = $scope; 

        this.Grid = {                               

            selectionSettings:{
                clientHandler:function(key,object,data){
                    console.log(key);
                    console.log(object);
                    console.log(data);                    
                    console.log(this);
                    return data;                        
                    //the scope of this function is different from the controller scope.                          
                    }              
           }
       }

       receiver(data){
             doSomething(data);
       }
    ...

The idea is that when I select an entry within the grid, the function within clientHandler is fired. I then want this function to pass that data to the receiver function in this class.

But since this clientHandler function and receiver() are in different scopes, I'm not able to do so directly using the this keyword.

Other answers on stackoverflow recommend using the $scope object to accomplish the same, but I'm not able to do so.

What is needed to make the clientHandler function call receiver() ?

Any guidance is earnestly welcomed. Thanks

Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39
  • Either that (call `receiver` yourself) or [save `this` in a `self` variable](https://stackoverflow.com/questions/3309516/when-to-use-self-in-javascript). – Adelin Dec 22 '17 at 08:46
  • That worked. Thanks – Saransh Kejriwal Dec 22 '17 at 08:56
  • While I'm able to see the change on my browser console, I'm not able to propagate the change caused by callbackHandler on my UI. I'm trying to call the `$doCheck()` lifecycle hook manually to reflect the same, but it doesn't make any difference. Which lifecycle hook can propagate this change to the UI ? – Saransh Kejriwal Dec 22 '17 at 11:33

2 Answers2

1

ES6 arrow functions exist to provide lexical this and avoid self = this trick, which is generally unnecessary in ES6:

clientHandler: (key,object,data) => {
  this.receiver(data);   
}  
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

Thanks Adelin for the heads-up

Here's the final working code:

class dashboardController {
    constructor(dashboardService, $scope) {
        this.$scope = $scope;      

        var self = this;

        this.Grid = {

            selectionSettings:{                
               clientHandler:function(key,object,data){
                   self.receiver(data);                 
            }                
        }

        receiver(data){
             this.selected = data;
             this.$scope.$apply(); //to propagate the change to the UI, if needed
         }

   }
Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39