Thursday, 24 November 2016

jquery - Why undefined elements inside ngOnInit method in Angular




I am initializing a library in my ngOnInit method as follows:




ngOnInit() {
this.$grid = jQuery('.grid').masonry({
// options
itemSelector: '.grid-item',//,
columnWidth: 384,
gutter: 24
});
......
}



then i am calling this method from that instance, inside ngOnInit as well:



 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
console.log(this.$grid);
} );


so it the method finally looks like this:




ngOnInit() {
this.$grid = jQuery('.grid').masonry({
// options
itemSelector: '.grid-item',//,
columnWidth: 384,
gutter: 24
});

// bind event listener

this.$grid.on( 'layoutComplete',function onLayout() {
console.log(this.$grid);
} );

}


But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.



I need to use that instance again inside that method to do something like this:




// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
this.$grid.masonry('layout');
} );


but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.



Any ideas?



Answer



This is because of the way you are binding your event.



In your code this refers to the execution context of the anonymous function you've passed to the on function (e.g. itself).



If you want to preserve the context of this, you have to use an arrow function like this:



this.$grid.on( 'layoutComplete', () => {
this.$grid.masonry('layout');
});


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...