Retrieving the Vue component object while inside the FullCalendar object initialized within the component

When using Full Calendar with VueJS, I ran into a problem where I needed to open a custom modal when clicking on a time slot in the calendar. The issue was that I couldn't call a function outside of the Full Calendar object to handle this. This is because using `this` inside Full Calendar would refer to that object rather than the Vue component object. I needed a way to access the Vue component object. Here are some unsuccessful attempts I made:

export default {
    name: 'MyComponent',
    methods: {
        myFunc () {
            // should get called from inside fullCalendar below
            this.$store.dispatch()  // this.$store works here since `this` refers to Vue component 
        }
    },
    mounted () {

        $('#calendar').fullCalendar({
        header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay,listWeek'
        },
        navLinks: true,
        eventLimit: true,
        defaultView: 'agendaWeek',
        editable: true,
        selectable: true,
        selectHelper: true,
        select: function (start, end) {
            console.log(this)   // refers to Full Calendar object
            console.log(this.$parent)   // getting null, need to call function in vue component
            console.log(this.myFunc()) // cannot do this since this will try to call a function in Full Calendar library
            console.log(this.$parent.$store) // getting null, need to get store that I defined 
        }
    }
}

Answer №1

One common challenge for new users in JavaScript is understanding scoping. The concept of this can be tricky to grasp because it is not fixed.

There are two approaches to address this issue. The first is using arrow functions, which maintain this bound to the original context:

select:  (start, end) => {
        console.log(this)   // should refer to your vue instance 
    }

Alternatively, you can save a reference to this at the beginning of your mounted function. This reference is commonly named self.

var self = this;

....

select: function (start, end) {
        console.log(self) // also points to your vue instance
    }

By employing this technique, you ensure that even if this changes within your callback, you can still access the initial object context through the self variable.

While arrow functions have largely replaced this method, it remains useful for supporting older browsers and expanding knowledge on the subject.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Elevate your website design by adding interactive Ripple Buttons using a combination of Javascript and

Recently, I came across a script that allows for an animation to occur when a button is clicked. However, I have encountered an issue where the script does not redirect to a link. (function() { var cleanUp, debounce, i, len, ripple, rippleContainer, rip ...

What is the best way to independently trigger changes in multiple copies of a Component?

Is there a way to use a computed property to trigger a boolean value within a component without impacting other copies of the same component? I have multiple instances of this component and want each one to trigger independently based on specific conditi ...

Sorting functionality in Vuetify's DataTable

I am currently utilizing the features of Vuetify Data Tables and have set the following props: :options.sync="filter_values" @update:options="updateFilterValues()" The issue I am facing is that I want to disable sorting for certain col ...

What is the best way to retrieve the post JSON data in the event of a 404 error?

When my service call returns a 404 error, I want to display the server's message indicating the status. The response includes a status code and message in JSON format for success or failure. This is an example of my current service call: this._trans ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

Webpack and Keycloak Integration: Content blocked because of MIME type ("text/html")

I am currently using VueJS for my frontend with Keycloak handling authentication, along with Webpack to bundle my code. Upon the initial application load, if the user is not authenticated, they are redirected to the Keycloak page. During this process, an ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

Invoke a function in JavaScript just once using a closure

I have a JavaScript function that I want to call only once, using closure. Here's the code snippet: function initialize() { let called = 0; return function() { if (called > 0) { return } else { called++; console.log(&a ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...

Guide to adding a personalized HTTP header to ajax request using JavaScript or jQuery

Is there a way to create a custom HTTP header using JavaScript or jQuery? I've tried the code below but it's giving me an error of 405 Method not Allowed. I'm using the POST method, but in the request it shows as OPTION. The status code is ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

What is the best way to align an element next to another using id or class?

I am looking to align the search element next to either "Media Heading 1" or "Media Heading 2" based on their id/class. For instance: Assume I have an element with the class of "media-item-1" and I aim to position the search div alongside that element us ...

Massive React State Array containing hundreds of Input elements, sluggish state updates triggered by onChange events

I am working on a React form that consists of multiple complex inputs, each with its own complex state. To manage the state of all these inputs, I have a parent component where each input is wrapped in a child component. The parent component holds a state ...