Wednesday, March 7, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...