【问题标题】:Calling a jQuery plugin inside itself在自身内部调用 jQuery 插件
【发布时间】:2012-06-17 21:13:21
【问题描述】:

我正在尝试创建类似彗星的东西。我有一个从 php 页面收集数据的插件。问题是我不知道如何调用插件本身。

如果它是一个函数,我可以这样:function j () {setTimeout(j(), 1000);},但我使用的是 jQuery 插件。

这是我的插件代码:

(function($) {
$.fn.watch = function(ops) {
    var
        $this_ = this,
        setngs = $.extend({
            'type'  : 'JSON',
            'query' : 'GET',
            'url'   : '',
            'data'  : '',
            'wait'  : 1000
        }, ops);

        if (setngs.type === '') {
            return false;
        } else if (setngs.query === '') {
            return false;
        } else if (setngs.url === '') {
            return false;
        } else if (setngs.wait === '') {
            return false;
        } else if (setngs.wait === 0) {
            setngs.wait = 1000;
        }

        var xhr = $.ajax({
            type        : setngs.query,
            dataType    : setngs.type,
            url         : setngs.url,
            success     : function(data) {
                var i = 0;
                for (i = 0; i < data.length; i++) {
                    var html = $this_.html(), str = '<li class="post" id="post-' + data[i].id + '"><div class="inner"><div class="user">' + data[i].user + '</div><div class="body">' + data[i].body + '</div></div></li>';
                    $this_.html(str + html);
                }
                setTimeout($this_, 1000);
            }
        });
};
})(jQuery);

上面写着setTimeout($this_, 1000); 这就是我遇到麻烦的地方。我不知道该怎么称呼这个插件。 $this_ 是我认为可能有效的方法,但我错了。这就是我需要更换的。

感谢您的帮助。

【问题讨论】:

    标签: jquery jquery-plugins plugins comet


    【解决方案1】:

    这里我可能会使用 JavaScript 的 call() 来调用一个函数。 MDN Documentation.

    因此,在插件中,您可以使用$.fn.watch.call(this) 调用它。传入call 的参数设置了它的作用域,因此传入this 以在同一作用域内调用它。

    我整理了一个基本示例,说明它在 JSBin 上的工作原理。

    您可以像这样在setTimeout 中使用它:

    setTimeout(function() { $.fn.watch.call(this) }, 1000);
    

    JSBin Example

    希望这会有所帮助:)

    【讨论】:

    • 怎么样 var $this_ = $.fn.watch; ?关闭已完成的函数应该允许调用......不是 100%,但对我来说似乎很有意义。 +1 尽管 .call 和关于此上下文的讨论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多