使用附加的函数/覆盖函数扩展jQuery插件

时间:2015-08-06 14:41:50

标签: javascript jquery plugins extend unslider

我需要扩展一个jQuery插件(https://github.com/idiot/unslider),以便使用另一个公共方法添加其他行为。

commit

我已经设法在调用

时访问公共方法
(function(){
    // Store a reference to the original remove method.
    var originalMethod = $.fn.unslider;
    // Define overriding method.
    $.fn.unslider = function(){

        // Execute the original method.
        originalMethod.apply( this, arguments );

        console.log( "Override method" );

        function test() {
            console.log("test called");
        }

        this.each(function() {
            // Operations for each DOM element
            console.log("each dom element?");

        }).data('unslider', {
            // Make test accessible from data instance
            test: test
        });

        return this;
    }
})(jQuery);

但是,我想保留unslider的旧行为,但是用另一个函数扩展插件。有没有人有想法?

我创造了一个小提琴,所以你可以检查发生了什么: 我的新函数被调用,但旧函数不见了: http://jsfiddle.net/b2os4s7e/1/

4 个答案:

答案 0 :(得分:1)

如果查看unslider的来源,可以看到它将Unslider实例存储在数据中:

    //  Enable multiple-slider support
    return this.each(function(index) {
        //  Cache a copy of $(this), so it
        var me = $(this),
            key = 'unslider' + (len > 1 ? '-' + ++index : ''),
            instance = (new Unslider).init(me, o);

        //  Invoke an Unslider instance
        me.data(key, instance).data('key', key);
    });

在你的代码中,你用自己的对象覆盖了这个对象。但是,滑块需要有一个Unslider实例。所以你要做的就是获取这个实例,然后用你自己的函数扩展它:

var key = $(this).data('key');
var obj = $(this).data(key);
obj.test = function() { console.log('Working!'); };

请参阅http://jsfiddle.net/b2os4s7e/2/

答案 1 :(得分:0)

只需定义:

$fn.unslider2 = function() { ... } 

您喜欢任何名称和行为。

答案 2 :(得分:0)

对于扩展,JQuery应该使用.fn.extend

(function($){ 
    $.fn.extend({
        helloworld: function(message){
            return this.each(function(){
                $(this).click(function(){
                    alert(message);
                });
            });
        }
    });
})(jQuery)

对象.fn.extend用于扩展jQuery的功能

答案 3 :(得分:0)

感谢您的回答!我是这样做的:

(function($){
    var originalMethod = $.fn.unslider;

    $.fn.extend({
        unslider: function(o) {
            var len = this.length;

            var applyMethod = originalMethod.apply( this, arguments );

            var key = applyMethod.data('key');
            var instance = applyMethod.data(key);

            //  Cache a copy of $(this), so it
            var me = $(this);

            if (instance) {
                instance.movenext = function (callback) {
                    return instance.stop().to(instance.i + 1, callback);
                };
                instance.moveprev = function (callback) {
                    return instance.stop().to(instance.i - 1, callback);
                };
            }

            return applyMethod.data(key, instance);


            });

        }
    });
})(jQuery)

关键是要将数据属性作为sroes建议来解决。

此外我需要应用原始方法,因为我需要旧方法。