调用插件方法

发布于 2025-01-07 17:45:44 字数 729 浏览 0 评论 0原文

如果我遵循插件创作指南,如何从公共方法调用私有方法,反之亦然?

我通常在 init 方法中声明私有方法,例如:

var methods = {
    init: function(options) {
        var settings = $.extend({
        }, options);

        return this.each(function() {
            var $this = $(this);
            var data = $this.data('griffin-editor');


            this.trimSpaceInSelection = function () {
                 //how do I call a public method here?
                 //to get the this context correct.
            }

            if (typeof data !== 'undefined') {
                return this;
            }

            //the rest of the code.

这可能是错误的做法?

How do I invoke a private method from a public one and vice versa if I follow the plugin authoring guide?

I usually declare the private methods within the init method like:

var methods = {
    init: function(options) {
        var settings = $.extend({
        }, options);

        return this.each(function() {
            var $this = $(this);
            var data = $this.data('griffin-editor');


            this.trimSpaceInSelection = function () {
                 //how do I call a public method here?
                 //to get the this context correct.
            }

            if (typeof data !== 'undefined') {
                return this;
            }

            //the rest of the code.

It might be the incorrect thing to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流殇 2025-01-14 17:45:44

如果“这个上下文正确”意味着你想要调用一些公共方法,并将其设置为在trimSpaceInSelection内部的值,那么你可以这样做:

....
this.trimSpaceInSelection = function () {
    methods.somePublicMethod.apply(this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod
}
....

如果你想将这个内部公共方法设置为当前的jQuery集合,那么:

....
this.trimSpaceInSelection = function () {
    methods.somePublicMethod.apply($this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod
}
....

If by 'this context correct' you mean that you want call some public method with this set to value which this has inside trimSpaceInSelection then you can do it like this:

....
this.trimSpaceInSelection = function () {
    methods.somePublicMethod.apply(this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod
}
....

And if you want set this inside public method to current jQuery collection then:

....
this.trimSpaceInSelection = function () {
    methods.somePublicMethod.apply($this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod
}
....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文