"Functionality of public methods in JavaScript plugin seems to be malfunction

Recently, I made the decision to redevelop a jQuery plugin using vanilla JavaScript. However, I have encountered an issue with getting the public methods to function properly. Despite all other logic working correctly, the public methods are not responding as expected. As an example, I have included the update method below.

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory(root));
    } else if (typeof exports === 'object') {
        module.exports = factory(root);
    } else {
        root.Plug = factory(root);
    }
})(typeof global !== "undefined" ? global : this.window || this.global, function(root) {

    var _settings;

    var defaults = {
        // default values
    }


    function runPlugin(){
        alert('it works')
    }

    var Plug = function(options) {

        var Plug = {};
        var settings;

        _settings = extend(settings || defSettings, options || {});

        var init = (function() {
            //init logic
            runPlugin();
            ...
        }());

        Plug.update = function(msg){
            alert(msg)
        }
    }

    return Plug;

});


var plug = new Plug({//settings...}); //works
var plug = new Plug().update('test'); //does not work

Answer №1

Make sure to reference this instead of Plug when adding methods within the Plug function:

this.update = ...

and not

Plug.update = ....

(I had to perform some tweaks to make your code sample work)

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory(root));
    } else if (typeof exports === 'object') {
        module.exports = factory(root);
    } else {
        root.Plug = factory(root);
    }
})(typeof global !== "undefined" ? global : this.window || this.global, function(root) {

    var _settings;

    var defaults = {
        // default values
    }


    function runPlugin(){
        alert('it works')
    }

    var Plug = function(options) {

        var settings;

        _settings = Object.assign(settings || defaults, options || {});

        var init = (function() {
            //init logic
            runPlugin();
           
        }());

        this.update = function(msg){
            alert(msg)
        }
    }

    return Plug;

});


var plug = new Plug({}); //works
var plug = new Plug().update('test'); 

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

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

The Bootstrap Tooltip seems to be glued in place

Utilizing jQuery, I am dynamically generating a div that includes add and close buttons. Bootstrap tooltips are applied to these buttons for additional functionality. However, a problem arises where the tooltip for the first add button remains visible even ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

Tips for keeping data on a page up-to-date using Node.js and Express

Currently delving into the world of Node.js and Express, I am immersed in a project that involves pinging websites and exhibiting the results on a web page. Leveraging HoganJS for templating as well. My primary focus is to decipher the steps necessary to m ...

Script that was generated dynamically is failing to run

I have a situation where I am adding a script tag, along with other HTML content, to my current document after making an AJAX call. However, the script is not executing as expected. //Function to handle response function(responseText){ document.getEle ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

The for loop encountered an uncaught type error when trying to access the .length property

Currently, I am working on a school project where the task is to create a basic social network posting application using Django and JavaScript. The purpose of using JavaScript is to dynamically load posts onto the webpage and update HTML components. I have ...

What is the method for populating a dropdown using ajax in the Jade template engine?

Looking to dynamically populate a dropdown based on the selection of another dropdown. Here's the code snippet: script. var b_name = []; function jsFunction() { var client = document.getElementById('drop_client'); var c_name = cli ...

When transferring files to the src/pages directory in Next.js, the custom _app and _document components are not recognized

The documentation for Next.js mentions that the src/pages directory can be used as an alternative to /pages. However, I encountered a problem when moving my custom _app.tsx and _document.tsx files into the src folder, as they were being ignored. If you cr ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

Tips for Sending <Div> Data to a Servlet

I attempted to pass the content of an entire div in a form action URL using JavaScript. However, when I try to retrieve this request parameter as a String on the servlet side, it is returning [object Object]. Below is my code for the form and JavaScript: ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Locating characters within a string using JavaScript

Currently, I am enrolled in JavaScript classes and have come across a challenging question. In this scenario, the task is to create a function named countLetters. This function will take two parameters: 1) sentence - this parameter should be of type stri ...

Check the File Format (not just the Extension) prior to Uploading

When uploading a file within an HTML form, you can validate the extension using JQuery's Validation plugin: <form enctype="multipart/form-data" id="form-id"> <input type="file" name="file-id" id="file-id" /> </form> To validate ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

Learn the process of obtaining a location and showcasing it on Google Maps

I am working on creating a program that utilizes modernizer to ask for the user's location and then displays it using Google Maps. So far, I have been able to use geolocation to determine the coordinates of the user's location and attempted to in ...