2013-03-13 53 views
2

我嘗試了一些常見的應用程序的具體行動移到jQuery插件由:什麼是使JQuery插件可擴展的方法?

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

但我不想申報的幾個擴展點:

$.fn.extpoint1 = function() {...} 
$.fn.extpoint2 = function() {...} 
... 

相反,我想使用語法糖,如:

$("#id").extpoint.func1().extpoint.func2() 

隨着定義:

$.fn.extpoint = {} 
$.fn.extpoint.func1 = function() { 
    this.val(); 
    this.data("ip"); 
    ... 
    return this; 
} 

並調用:

$("#id").extpoint.func1(...) 

this指向$.fn.extpoint(字典與func1func2,...的元素),而不是原來的jQuery對象,當func1評價。

是否有可能使jQuery插件可擴展?

PS。可以將函數名稱作爲第一個參數傳遞給$.fn.extpoint,並實現$.fn.extpoint('extend', func)調用來擴展(保存到名稱和實現之間的內部字典關聯)擴展點。在這種情況下,使用情況是這樣的:

$("#id").extpoint('func1', ...).extpoint('func2', ...) 

,但我期待的方式讓更多的語法糖...

+1

它不會以這種方式工作:'$( 「#ID」)extpoint.func1()extpoint.func2()'因爲FUNC1和FUNC2將不能訪問'$(。 「#id」)' – 2013-03-13 15:14:47

+0

@KevinB Yea,我明白了,但是想方設法避免這種情況,並且有一些未知的技巧...... +1 – gavenkoa 2013-03-13 17:44:06

+1

一年或兩年前,jQuery論壇上發佈了一篇文章,其中有人想出了一個這樣做的工作方式,但它非常複雜,我不記得它是如何完成的。我建議在那裏搜索它,我找不到它。 – 2013-03-13 17:46:01

回答

1

Here是創建插件的概述。我相信你所問的是「鏈接」。這正是jQuery如此易於使用的原因,並且您希望確保您正確實施它是一件好事。

關於鏈接開發插件時要記住的關鍵是從您的方法總是return this;。這是什麼讓你保持連鎖行進。

+0

對不起,我不談論鏈接。但關於製作** jQuery插件**可以以某種一致的方式擴展爲** jQuery **本身... – gavenkoa 2013-03-13 17:42:47

2

我問的任務很難實現。

Official docs說:

在任何情況下應單插件不斷要求多個命名空間中jQuery.fn對象

(function($){ 
    $.fn.tooltip = function(options) { 
    // THIS 
    }; 
    $.fn.tooltipShow = function() { 
    // IS 
    }; 
    $.fn.tooltipHide = function() { 
    // BAD 
    }; 
})(jQuery); 

這是一種勸阻,因爲它雜波了$.fn命名空間。爲了解決這個問題,你應該把所有插件的方法都收集到一個對象字面值中,並通過將該方法的字符串名稱傳遞給插件來調用它們。

另一種方法是保持鏈接thishttp://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js

所以你的電話看起來像:

$.fn.addPlugin('test2', { 
    __construct : function(alertText) { alert(alertText); }, 
    alertAttr : function(attr) { alert($(this).attr(attr)); return this; }, 
    alertText : function() { alert($(this).text()); return this; } 
}); 

$('#test2').bind('click', function() { 
    var btn = $(this); 

    btn.test2('constructing...').alertAttr('id').alertText().jQuery.text('clicked!'); 

    setTimeout(function() { 
      btn.text('test2'); 
    }, 1000); 
}); 

一些相關鏈接:

舊風格的插件extention: