1

I have written some relatively simple jQuery plug-ins, but I am contemplating writing something more advanced in order to keep commonly used methods on the site easily accessible and DRY

For example, I might have something like this for a structure:

plugin
- popup
- element
...

=== popup ===
- login
- product
...

=== element ===
- shoppingCart
- loginStatus
...

So, to bind a popup login popup event, I'd like to be able to do: $('#login_button').plugin.popup.login();

What's the best way to do this? Is there a better way of achieving what I want to do?

Cheers,

4

2 に答える 2

1

Farhan Ahmadが行った方法は、ほぼ正しかったです...ニーズに合わせて、より深いレベルが必要です。実装は次のようになります。

jQuery.fn.plugin = function(){
  //"community" (global to local methods) vars here.
  var selectedObjects = this; //-- save scope so you can use it later

  // return the objects so you can call them as necessary
  return {  
            popup: { //plugin.popup
                    login: function(){ //plugin.popup.login
                         //selectedObjects contains the original scope
                         console.log(selectedObjects);
                    },
                    product: function(){} //plugin.popup.product
            },
            element: { //plugin.element
                    shoppingCart: function() {}, //plugin.element.shoppingCart
                    loginStatus: function() {} //plugin.element.loginStatus
            }
         }
}

だから今あなたが呼ぶならば: $("#someDiv").plugin.login();結果は期待通りになるでしょう。これがお役に立てば幸いです。

于 2012-06-12T23:21:06.240 に答える
1
jQuery.fn.messagePlugin = function(){
    var selectedObjects = this;
    return {
         saySomething : function(message){
                          $(selectedObjects).each(function(){
                            $(this).html(message);
                          });
                          return selectedObjects; // Preserve the jQuery chainability 
                        },
         anotherAction : function(){
                        //...
                        return selectedObjects;
                        }
           };
}

次のように使用します。

$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');

選択されたオブジェクトは messagePlugin クロージャに格納され、その関数はプラグインに関連付けられた関数を含むオブジェクトを返します。各関数では、現在選択されているオブジェクトに対して目的のアクションを実行できます。

于 2012-06-07T23:56:42.687 に答える