jQuery插件:如果我想调用类似$('selector')的插件.plugin.group.method(),我该如何实现呢?

时间:2012-06-02 23:47:19

标签: javascript jquery

我已经编写了一些相对简单的jQuery插件,但我正在考虑编写一些更高级的东西,以便让网站上常用的方法易于访问和干燥

例如,我可能对结构有这样的东西:

plugin
- popup
- element
...

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

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

因此,要绑定弹出式登录弹出事件,我希望能够: $( '#login_button需要')plugin.popup.login();

最好的方法是什么?有没有更好的方法来实现我想做的事情?

干杯,

2 个答案:

答案 0 :(得分: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闭包中,该函数返回一个包含与插件关联的函数的对象,在每个函数中,您可以对当前选定的对象执行所需的操作。

答案 1 :(得分: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();结果将符合预期。我希望这会有所帮助。