Retrieve the JS function within a return statement

Is there a way to call the showDashboard and showTimeline functions using the $(...) function in the code snippet below?

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

    $("#right-menu-dashboard").click(function(){
        // Wanting to access showDashboard here...
        showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // ...and calling showTimeline here.
        showTimeline();
    });

    return {

        showDashboard: function() {
            // Implement functionality for showDashboard here
        },

        showTimeline: function() {
            // Implementation of showTimeline goes here
        }
    }
});

Answer №1

There are multiple ways to achieve this. One approach could be:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){

    $("#right-menu-dashboard").click(function(){
        // Access the showDashboard function here
        showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // Access the showTimeline function here
        showTimeline();
    });

    function showDashBoard() {
        // Some code here
    }

    function showTimeline() {
        // Additional code here
    }

    return {
        showDashboard: showDashboard,
        showTimeline:  showTimeline
    };
});

Alternatively, a more concise modification:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
    var obj;

    $("#right-menu-dashboard").click(function(){
        // Access the showDashboard function here
        obj.showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // Access the showTimeline function here
        obj.showTimeline();
    });

    obj = {

        showDashboard: function() {
            // Some code here
        },

        showTimeline: function() {
            // Additional code here
        }
    };
    return obj;
});

Another cleaner option:

define(["jquery", "bootstrap", "./timeline"], function($, bootstrap, timeline) {

$(function(){
    var obj = {

        showDashboard: function() {
            // Some code here
        },

        showTimeline: function() {
            // Additional code here
        }
    };

    $("#right-menu-dashboard").click(function(){
        // Access the showDashboard function here 
        obj.showDashboard();
    });

    $("#right-menu-timeline").click(function(){
        // Access the showTimeline function here
        obj.showTimeline();
    });

    return obj;
});

It's important to note that there is a distinction between these approaches. The usage of this may vary based on whether you choose the first method or the latter two. If your functions rely on this, it becomes crucial to consider which implementation suits your requirements.

Answer №2

It is important to establish the functions beforehand, implement them, and then deliver their output.

define(['bar'], function(bar) {
    function displayMenu() {...}

    $('#panel-menu').click(function() {
        displayMenu(); 
    });

    return {
        displayMenu: displayMenu
    };
});

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

transfer chosen data from a text box to a dropdown menu

Looking for: I am in need of a feature where users can input a movie title in a textbox and upon clicking the "move to selectedlist" button, the entered movie title should be added to a dropdown list that displays all the movies selected by the user. Addit ...

Experiencing difficulties with ng-modal in the controller invocation

These are the steps I followed: 1) First, I downloaded the script file from: https://github.com/doodeec/dcom-angular-dialog 2) Next, I included it in both my webpage and application: var summariesApp = angular.module('summariesApp', ['ui ...

Best locations for placing files when integrating Javascript into Wordpress

I have been struggling to make JavaScript work and determine the correct location to place the files. After attempting various methods, I am now wondering what the most logical approach would be. Despite spending a week on this task, the lack of a tutoria ...

Can an Updatepanel control be added to a webpage using Javascript or JQuery?

I'm currently working on a project that involves allowing users to drag icons representing user controls onto a web page. For the desired functionality, these user controls must be contained within an updatepanel (or a similar AJAX-enabled frame) so ...

Gatsby is encountering an error when trying to locate the necessary resources for the error page, leading to React not being

During the development of my Gatsby Project, everything was working correctly with Gatsby Develop. However, I encountered an issue when I started the build process and deployed the website. Upon opening the website in a browser, I received the following e ...

List of elements in JSON file with key value pairs and their indexes

Is there a way to create a function that can scan through a JSON file and identify the index where a specific key-value pair is located within an object? For instance, if we were searching for value: '100.0' in the following JSON data, the functi ...

Implementing hover-over tooltips with JavaScript and HTML

New JS function: function DisplayToolTip() { let x = event.clientX; let y = event.clientY; document.getElementById('divToolTip').style.left = x + 'px'; document.getElementById('divToolTip').style.top = y + &ap ...

Showing a div with seamless elegance

XHTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>example</title> </head> <style > body{ background: black; } ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

Execute a method within a nested component and trigger a function within the main component

Looking to retrieve states of a country upon change and send handleChange up to the parent for the Child component, the following code is rendered: <select className="floating-select" id = "country" type ="text" ...

Implementing crossfilter in Highcharts necessitates altering the title of the x-axis from 'categories'

My current goal is to incorporate crossfilter functionality into my highcharts project. Within the dataset, there exists a key labeled 'date'. The values within the date key are structured as 'yyyy-mm' (e.g., 2018-04). During implement ...

What is the best way to customize the behavior of multiple instances of ng-include within the same view?

My goal is to have unique behavior for each instance of the calendar that I include multiple times in my main HTML view. Specifically, I want to display 3 different dates based on the day selected in each calendar. In my main HTML view, I have included th ...

Define the starting value for Framer Motion's useCycle by taking into account the width of the screen

With the help of Framer Motion's useCycle hook, I am able to toggle the visibility of my sidebar. The desired behavior is to have the sidebar open by default on desktop (window width > 480px) and closed by default on mobile devices. To achieve thi ...

Update the base path from /docs/ to /home/ for Docusaurus websites

I have been attempting to change the default docs path to home in order to organize all my "documentation" files under the home directory like home/doc1. I referred to this guide: and made modifications to my docusaurus.config.js file as follows: module.e ...

iOS iframe remains unscrollable only when switching from portrait to landscape orientation

I have a scrollable iframe set up on iOS like this: <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; overflow: scroll; -webkit-overflow-scroll: touch; ..."> <iframe style="height: 600px, ..."> </iframe> </d ...

Javascript recursive method for fetching data entries

Seeking a solution to retrieve interconnected records based on a parent column, where the relation can be one or many on both ends. After attempting a recursive function without success, I found my code became overly complex and ineffective. Is there a st ...

Alternative for str.decode('unicode_escape')

Is there a JavaScript equivalent for the str.decode('string_escape') function in Python? var data = {k: 'test\\"ing\\:"'}; JSON.stringify(data).decode('string_escape') >>> '{"k": "test"ing""} ...

Wrap the words around to fit a rectangle with a specific ratio, rather than a specific size

Does anyone have a solution for breaking text at word boundaries to perfectly fit a rectangle with a specific approximate ratio, such as 60:40 (width:height)? Please note that this is not just about setting a width limit (e.g. 80 characters or 600px) and ...

Issue with Vuejs where changes are made to the parent array, but the child component does not detect those

I'm facing an issue where my parent component has the following code: {{ fencing }} <FencingTable v-if="fencing.length > 0" :fencing="fencing" :facility="facility" /> get fencing() { return this.$sto ...

Why isn't the Angular Google Maps Displaying in my Template View?

After configuring Angular Google Maps and following the provided steps, I am facing an issue where the map is not loading on the directive without any error. Below is the code snippet: Controller app.controller('MapCtrl', [ '$scope&apo ...