javascript - 如何从插件外部调用插件的函数

标签 javascript jquery function plugins jquery-plugins

我知道这是 stackoverflow 中的一个老问题。但对我来说这是新的,我已经寻找了解决方案,但没有找到我可以理解的解决方案。我有一个插件,其中有一些功能。现在,我想在选择选项上的事件发生变化时访问其中一个函数。但我的问题是我无法从插件外部访问该功能。不过我是插件开发的新手。

这是我的插件:

(function($, window, document, undefined) {
    var Spec = {
        init: function(options, ele) 
        {
            var self = this;
            self.elem = ele;
            self.$elem = $(ele);

            self.findPro = (typeof options === 'string') ? self.findPro = options : self.findPro = options.findPro;
            self.options = $.extend({}, $.fn.specpro.options, options);
            if (self.options.findPro === 'latest') {
                self.latestPro();
            }
        },
        .
        .
        .
        filter:function(filFor){
            console.log($('.chzn-select').val());

        }
    };
    $.fn.specpro = function(options) {
        return this.each(function() {
            var spec = Object.create(Spec);
            spec.init(options, this);
        });
    };
    $.fn.specpro.options = {
        findPro: 'latest'
    };
})(jQuery, window, document);

我尝试的是:

$(function(){
 var mn=$('#lp').specpro({findPro:'latest'});
 $('.chzn-select').chosen().change().mn.filter('latest');
});

谁能告诉我。如何从插件外部调用函数filter

直播Fiddle

最佳答案

该函数位于“Spec”对象中,并且在自调用匿名函数的范围内:

(function($, window, document, undefined) {
... code ...
})(jQuery, window, document);

因此,只有该匿名函数内的代码才能访问Spec.filter()。要访问 Spec 变量,它需要位于全局范围内。

当某物位于“全局”范围内时,这意味着它附加到全局对象(在大多数情况下,这是窗口)。

举个例子

var test = {
'hello' : function (){
    alert('hello world');
    }
}

功能上与以下相同:

window.test = {
'hello' : function (){
    alert('hello world');
    }
}

所以它们都可以被称为 test.hello() 或 window.test.hello() 'test' 对象位于全局范围(窗口)中。

现在让我们将第一个示例放入匿名函数中。

(function(){
var test = {
'hello' : function (){
    alert('hello world');
    }
}
// call the function
test.hello();

})();

如果您尝试这样做,它将显示警报。但是,如果您稍后厌倦了调用 test.hello();,您会得到类似以下内容的信息:

ReferenceError: test is not defined

对象 test 及其 hello() 函数位于匿名函数作用域中,而不是全局作用域中。

现在又是相同的函数,但我们将测试直接附加到窗口(全局范围)。

(function(){
window.test = {
'hello' : function (){
    alert('hello world');
    }
}
// call the function
test.hello();

})();

现在您可以随时在匿名函数之外进行 test.hello() 。您可以有多个级别的范围。

关于javascript - 如何从插件外部调用插件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569936/

相关文章:

javascript - ng-submit 不起作用

javascript - 在reduce/jQuery中调用函数

javascript - 在输入占位符中调用组件

java - 更改类实例中函数的主体

javascript - HTML5 Canvas 从浏览器拖出到桌面

javascript - __doPostBack 不是一个函数

javascript - 在javascript中查找给定两天之间存在的天数、月数和年数

php - ajax登录问题

javascript - 将最后一个 td 带到 tr knockout 中的下一行

python - 如果 len(list) 不能被 3 整除,则排除函数中的最后一项。 python 2.7.1