質問

いを作りたいと思っているjQueryプラグインとのAPIとして思ったこと。

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

くことが、この

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

基本的にではなく、有名前空間毎法行為に似たものにjQueryので、そういった"範囲"の方法をカスタムapi $("#chart).pluginName() 思い返すオブジェクトになる get, attr, find, では、他のところは完全に書き換える。

思いやって多いといえるでしょうがまとめられることにより、条約(いのですか?), もう、読みやすくする工夫がなければ、おそらくより最適化され、二つのオプションです。あなたはどう思いますか。

役に立ちましたか?

解決

私の実験のアイデアです。

そうだけなのに変更する機能は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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top