Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 FullCalendar callback inaccessible properties

I have an angular2 app where i have a Full Calendar component. I want to display a dialog on click of a full calendar event using the eventClick callback. I have the following code to do this:

export class ScheduleComponent implements OnInit{

events: CalendarEvent[];
display: boolean;
tables: SelectItem[];
selectedTable: string;

ngOnInit(){
    this.display = false;
    this.scheduleService.GetAllEvents().subscribe((data: CalendarEvent[]) => 
            { 
                this.events = data;
                var calendar: JQuery = $("#calendar");
                (<any>calendar).fullCalendar({
                    eventClick: function(event) {
                        this.display = true;
                        return false;
                    }
                });
            });
}

}

This is a very simplified version but should give all the information needed.

My problem is that the this.display = true line inside the eventClick callback does not seem to be able to see the display property.

Does anyone know why this is and how i could fix it?

Thanks,

like image 523
DaRoGa Avatar asked Aug 03 '26 13:08

DaRoGa


2 Answers

Typically after posting a question, i have now worked out a resolution.

The solution for anyone else struggling with this is to use the 'fat arrow' notation.

So instead of this:

eventClick: function(event) {
                        this.display = true;
                        return false;
                    }

I used this:

eventClick: (event) => {
                        this.display = true;
                        return false;
                    },

Im not too sure how this works as it was just trial and error. So if anyone does know why and can explain it then i would be very interested to find out why.

like image 75
DaRoGa Avatar answered Aug 05 '26 11:08

DaRoGa


The challenge you were facing had something to do with scope. At runtime the value of this changes and there fore display wont be accessible.

Lexical scoping is one of the ways you can solve this and thats what you have done above.

You can also bind the context of the method to the this so it executes within that context.

You can do this using the javascript bind method

like image 44
Edwin Kato Avatar answered Aug 05 '26 11:08

Edwin Kato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!