6

次のような API を使用して jQuery プラグインを作成したいと思います。

$("#chart").pluginName().attr("my_attr");

これらの代わりに:

$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");

基本的に、 jQuery のメソッドと同様に機能するすべてのメソッドに名前空間を設定する代わりに、メソッドをカスタム API に「スコープ」したいと思います$("#chart).pluginName()。.getattrfind

これは慣習に反するのであまり好まれないアイデアだと思いますが (そうですか?)、上記の 2 つのオプションよりも簡単で読みやすく、おそらくより最適化されています。あなたの考えは何ですか?

4

1 に答える 1

2

という発想で実験中です。

プラグインが受け取る jQuery オブジェクトの関数を変更して、それを返すことができるようです。

このようなもの:

$.fn.tester = function() {  // The plugin

    this.css = function() {  // Modify the .css() method for this jQuery object
        console.log(this.selector);   // Now it just logs the selector
        return this;     // Return the modified object
    }
    return this;   // Return the modified object

}

http://jsfiddle.net/EzzQL/1/ (オリジナルから .html() も上書きするように更新)

$.fn.tester = function() {
    this.css = function() {  
        console.log(this.selector);  // This one logs the selector
        return this;
    }
    this.html = function() {
        alert(this.selector); // This one alerts the selector
        return this;
    }
    return this;
};

// Because .css() and .html() are called after .tester(),
// they now adopt the new behavior, and still return a jQuery
//    object with the rest of the methods in tact
$('#test1').tester().css().html().animate({opacity:.3}); 


// .css() and .html() still behave normally for this one
//    that doesn't use the plugin
$('#test2').css('backgroundColor','blue').html('new value');​

編集:

または、カスタム メソッドを適用する必要がある要素をキャッシュする場合は.apply()、メソッドを使用する前にメソッドをキャッシュすることができます。

上記の例に基づいて構築するには:

var $test1 = $('#test1');  // Cache the elements

$.fn.tester.apply($test1,[this]);  // apply() the new methods

$test1.css().html().animate({opacity:.3});  // Use the new methods

</p>

于 2010-06-15T21:15:29.640 に答える