2009-06-25 29 views
15

我的目標是能夠調用我的JQuery插件中的函數。如何調用嵌套在JQuery插件中的函數?

什麼是正確的語法?

例如,這不起作用:

<a href="#" id="click_me">Click Me</a> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script> 
(function($) { 
    $.fn.foo = function(options) { 
     do_stuff = function(){ 
      console.log("hello world!"); // works 
      do_other_stuff = function(){ 
      alert("who are you?"); 
      } 
     } // function 
    } // function 
})(jQuery); 

$("body").foo(); 

$("#click_me").click(function(){ 
$.fn.foo.do_stuff.do_other_stuff(); // doesn't work 
}); 

</script> 

回答

35

當您將功能賦予變量沒有var關鍵字,他們要麼覆蓋該名稱的局部變量或添加到全局命名空間。 (所以你的do_stuff是一個全局函數,這是不是你想要的)

做你想做的一種方法是明確地給你想要你的函數駐留的地方。

(function($) { 
    $.fn.foo = function(options) { 
     // whatever $().foo() should do 
    }; 

    $.fn.foo.do_stuff = function() { 
     console.log("hello world!"); 
    }; 

    $.fn.foo.do_stuff.do_other_stuff = function(){ 
     alert("who are you?"); 
    }; 
})(jQuery); 

編輯

這工作,因爲在JavaScript中的所有功能都是對象,這意味着你可以將值分配到任意屬性。

如果你要訪問其他功能的變量,你可以移動的定義,其他的像內:

$.fn.foo.do_stuff = function() { 
    console.log("hello world!"); 
    $.fn.foo.do_stuff.do_other_stuff = function(){ 
     alert("who are you?"); 
    }; 
}; 

,但是這將意味着,一旦你運行其他函數的函數只定義,每次運行該函數時都會覆蓋最後一個定義。

可能是更理想的解決方案將是使每個函數返回一個包含像這樣的嵌套函數的對象:

(function($) { 
    $.fn.foo = function(options) { 
     // whatever $().foo() should do 

     var do_stuff = function(do_stuff_args) { 
      console.log("hello world!"); 
      // do stuff with options and do_stuff_args 

      var do_other_stuff = function(other_args) { 
       alert("who are you?"); 
       // here you have access to options, do_stuff_args, and other_args 
      }; 

      return { 
       do_other_stuff: do_other_stuff 
      }; 
     }; 

     return { 
      do_stuff: do_stuff 
     } 
    }; 
})(jQuery); 

和使用

foo().do_stuff(some_options).do_other_stuff(other_options); 

var a = foo(stuff).do_stuff(some_options); 
a.do_other_stuff(foo); 
a.do_other_stuff(bar); 
+0

調用它我真的不知道爲什麼這個工作。我以爲$ .fn.foo可能是一個函數或具有屬性do_stuff的對象,但在您的示例中它是兩者。這是可能的JavaScript?你能給我一個指針來閱讀這個功能嗎?或者我在這裏弄錯了什麼? – 2009-06-25 07:15:44