简体   繁体   English

在jquery插件中链接非jquery方法

[英]Chain non-jquery methods in a jquery plugin

Let's say I write a jquery plugin that has a method that adds two values and sets the html to that value. 假设我写了一个jquery插件,它的方法可以添加两个值并将html设置为该值。 I can chain it one way, but not the other and I want to understand why, and how I can make sure I can chain both ways. 我可以采用一种方式进行链接,但不能采用另一种方式,并且我想了解原因以及如何确保可以采用两种方式进行链接。

$.fn.foo = function() {
    this.result = 0;

    this.doMath= function(a, b) {
        this.result = a + b;
        this.html(this.val);
        return this;
    }

    return this;
}

var link = '<a href="#">Link</a>'
// works as expexted
var a = $(link).foo().doMath(1,2).appendTo('body')
// does not work, likely because appendTo returns jquery
var b = $(link).foo().appendTo('body').doMath(1,2)

https://jsfiddle.net/j7ut1f30/1/ https://jsfiddle.net/j7ut1f30/1/

After 2 weeks of trying everything, I finally acheived my goals. 经过2周的尝试,我终于实现了自己的目标。

class $Util {

    static $wrapper(self) {
        if (!self.$wrapper)
            throw new ReferenceError('$Util.$wrapper: $wrapper not defined in context of first argument');
        $.each($Util.jqueryPrototype, function(i, e) {
            self[e] = function() {
                self.$wrapper[e](...arguments);
                return self;
            }
        });
    }
}

$Util.jqueryPrototype = Object.getOwnPropertyNames($.prototype);

class foo {
    constructor() {
        this.$wrapper = $('p')
        $Util.$wrapper(this);
        return this;
    }
    test() {
        console.log('j')
        return this;
    }
}
var s = new foo();
s.css('color', 'red').test().appendTo('body').test().css('color','green')

https://jsfiddle.net/24r6uxs1/ https://jsfiddle.net/24r6uxs1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM