您可以使用JS对象作为JQuery插件的接口吗? [英] Can you use a JS object as the interface for a JQuery plugin?

查看:54
本文介绍了您可以使用JS对象作为JQuery插件的接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过以下线程:如何创建一个带有方法的jQuery插件?,尽管有很多关于多功能插件的解决方案,但我很想知道是否有可能使用一个对象,以免出现像$("selector").plugin().dostuff()这样的丑陋结构,并且而是可以更像这样使用它:$("selector").plugin.dostuff(),即'plugin'是一个对象而不是一个函数.

I've had a look at this thread: How to create a jQuery plugin with methods?, and while there are plenty of solutions regarding multi-function plugins, I'm interested if it's possible to use an object so that you don't have ugly constructions like $("selector").plugin().dostuff(), and instead can use it more like this: $("selector").plugin.dostuff(), ie 'plugin' is an object not a function.

我可以这样编写插件:

$.fn.plugin = {
    dostuff: function() {},
    domorestuff: function(){}
};

但是内部函数将无法访问首先调用它的JQuery对象,因为this返回插件对象.是否有任何方法可以围绕可与JQuery一起使用的对象构建插件?

But then the inner functions won't have access to the JQuery object that's calling it in the first place, as this returns the plugin object. Is there any way to structure a plugin based around an object that would work with JQuery?

推荐答案

不,由于您给出的原因:您丢失了this,并且this在编写插件时非常重要.要获取this,您的插件必须是一个函数.

No, and for the reason you gave: You lose this, and this is hugely important when writing a plugin. To get this, your plugin must be a function.

基本上,您可以通过三种方法来实现方法:

You basically have three ways of implementing methods:

  1. 使用字符串参数,例如:

  1. Using string arguments, e.g.:

$("selector").plugin("dostuff");

...在插件函数中分派到处理程序方法的位置.这是迄今为止最流行的方式.这是jQuery UI,Bootstrap和其他应用程序使用的方式.完整的示例如下.

...where you dispatch to your handler methods within the plugin function. This is by far the most popular way. It's the way used by jQuery UI, Bootstrap, and others. Full example of this below.

使用您所说的难看的构造",即您的插件是一个函数,它会返回一个具有您可以调用的函数的对象(每次都会保存一个新对象,以保存this).

Using the "ugly construction" as you put it, where your plugin is a function and it returns an object (a new object each time, to preserve this) with functions you can call.

使用某种类型的前缀向jQuery添加多个插件方法,而不仅仅是一个,因此最终以$("selector").pluginDoThis();$("selector").pluginDoThat();$("selector").pluginDoTheOther();结尾.关键是使用前缀来避免名称冲突.很久以前,我只看过一次,而且很久没见到该插件了.并不是很受欢迎的选择.

Adding several plugin methods to jQuery rather than just one, using a prefix of some kind, so it ends up being $("selector").pluginDoThis(); and $("selector").pluginDoThat(); and $("selector").pluginDoTheOther(); The key is to use a prefix to avoid name conflicts. I've only seen this done once, a long time ago, and I haven't seen that plugin in a while. Not really a popular choice.

我最近刚刚发布了其他答案,其中显示了#1的完整模式(在他们的情况下,方法是callThisdestroy),例如:

I just recently posted this other answer showing the full pattern for #1 (in their case, the methods were callThis and destroy), e.g.:

// Create the plugin
(function ($) {
    var methods = {
        init: function(options) {
            // Determine options
            var opts = $.extend({
                opacity: 0.5             
            }, options);

            // Remember them
            this.data("pluginname", opts);

            // Initial stuff
            this.css("opacity", opts.opacity);
        },

        callThis: function(opts) {
            // Use 'opts' if relevant
            this.css("display","none");
        },

        destroy: function(opts) {
            this.removeData("pluginame");
            this.css("display", "").css("opacity", "");
        }
    };

    jQuery.fn.pluginname = function (options) {
        var method, args;

        // Method?
        if (typeof options === "string") {
            // Yes, grab the name
            method = options;

            // And arguments (we copy the arguments, then
            // replace the first with our options)
            args = Array.prototype.slice.call(arguments, 0);

            // Get our options from setup call
            args[0] = this.data("pluginname");
            if (!args[0]) {
                // There was no setup call, do setup with defaults
                methods.init.call(this);
                args[0] = this.data("pluginname");
            }
        }
        else {
            // Not a method call, use init
            method = "init";
            args = [options];
        }

        // Do the call
        methods[method].apply(this, args);
    };
})(jQuery);

// Example usage
function doInit() {
  $("#target").pluginname();
  setTimeout(doCallThis, 700);
}
function doCallThis() {
  $("#target").pluginname("callThis");
  setTimeout(doDestroy, 700);
}
function doDestroy() {
  $("#target").pluginname("destroy");
  setTimeout(doInit, 700);
}

setTimeout(doInit, 700);

<div id="target">This is the target</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于您可以使用JS对象作为JQuery插件的接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆