【问题标题】:How to write jquery chainable functions for local using?如何编写 jquery 可链接函数以供本地使用?
【发布时间】:2013-02-22 16:56:28
【问题描述】:

如何编写可链接的函数但不污染 $.fn ?编写仅在我的插件内部使用的函数。有可能吗?

$('.myclass').makeSomething().andOneMoreFunction().andLast();

这是正确的方法吗?

UPD。 就我而言,最好的解决方案是扩展方法:

String.prototype.getMyLength = function(){return this.length;}

现在我可以将此函数应用于任何字符串,如下所示:

var mystring = "test";
mystring.getMyLength();

或者

"teststring".getMyLength()

并使其可链接:

String.prototype.getMe = function(){return this;}
"string".getMe().getMe().getMe().getMe().getMe();

感谢您的回答!

【问题讨论】:

    标签: javascript jquery method-chaining


    【解决方案1】:

    您可以将所有您想要的链接。如果您自己定义了$.fn,那么您在函数结束时return this 很重要。

    如果你想自己写一些javascript,你也可以链!这仅取决于您返回的内容。因此,如果您返回一些其他对象,您可以从该对象链接。返回值用于此。

    示例

    var obj = {
        test : function(){ 
            alert("Y"); 
            return this; 
        },
        test2 : function(){ 
            alert("2"); 
            return this; 
        }
    }
    obj.test().test2(); // And so on since it returns this
    

    jQuery 插件 API

    $.fn.test = function(){
        var methods = {
            method0 : function(){
                alert("method0");
                return this;
            }
        };
        return methods;
    }
    var api = $("obj").test(); // Returns methods
    api.method0(); // Calling a function from the returned methods.
    // OR
    $("obj").test().method0();
    

    上面的函数不再是 jQuery 可链接的。所以你不能使用$("obj").test().addClass("test"),因为你返回了你自己的API!

    【讨论】:

    • 但问题是“如何做到不污染$.fn”。如果您只想在插件内部使用这些功能并希望避免名称冲突,我认为这是非常合理的。
    • 我的示例 2 是否回答了这个问题?我给出了两个使用链接的例子。第二个返回一个 API。所以内部也可以这样使用。仅取决于您的返回值。 @PaulS。这只是伪代码。
    【解决方案2】:

    您可以通过使用插件函数的第一个参数来指定选择的方法来避免污染;比如

    (function () {
        var o = { // object holding your methods
            'bar': function () {console.log('bar', this); return this;},
            'foobar': function () {console.log('foobar', this); return this;}
        };
        $.fn.foo = function (method /*, args*/) {
            return o[method].apply(
                this,
                Array.prototype.slice.call(arguments, 1) // pass your args
            );
        };
    }());
    

    然后

    $('something').foo('bar').foo('foobar');
    /*
    bar, thisobj
    foobar, thisobj
    */
    

    这样您也可以正常访问 jQuery 对象。

    【讨论】:

      【解决方案3】:

      当您调用a.foo() 时,将调用函数foo,并将this 设置为a。您可以利用这一点。

      还记得 表达式 a.foo() 的计算结果是您在函数中的 returnd。

      所以,只需返回this

      然后a.foo() 计算回a(a.foo()).bar() 等效于调用a.foo() 然后调用a.bar()...即a 上的链式操作!

      $.fn 并不是特别神奇 - 它只是以与您将要使用的相同的方式使用上述逻辑。

      【讨论】:

        猜你喜欢
        • 2011-03-17
        • 2022-11-02
        • 1970-01-01
        • 2022-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-12
        • 1970-01-01
        相关资源
        最近更新 更多