Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Javascript plugin public methods not working

Decided to rebuild an jQuery plugin in vanilla JS I run into an issue, I cant seem to get the plublic methods to work. All other logic works but not the public mehtods. I have include the update method as an example.

(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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Within the Plug function, you should be referring to this not Plug to add methods. So

this.update = ...

not

Plug.update = ....

(Note I had to do a bit of jiggery-pokery to get your sample running)

(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'); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...