开发者

newbie jQuery plugin issue

I'm just getting into jQuery plugins and I wanted to do a sort of 'hello world' exercise with a barebones object-oriented plugin template. But I can't get the console.log statement in the setup() function below to display in a firebug console window.

I call the plugin like so:

<script type="text/javascript" src="myPlugin.js" >
<script type="text/javascript"> 
  $(document).ready() {
    $('ul').myPlugin();
  });
</script>

myPlugin.js:

;(function($) {

  $.fn.extend({
      myPlugin: function(options) {
          return this.each(function() {
              new $.MyPlugin(this, options);
          });
      }
  });

  $.MyPlugin = function(element, options) { 
      var defaults = {          
          helloText: "hello World"          
      }

      this.options = $.extend({}, defaults, options || {}); 

      this.setup();     
  };

  $.extend($.MyPlugin.prototype, {

    setup: function() {
        console.log(this.helloText);        
    }   
  });   
})(jQuery);

Like I said, the console.log statement in the 开发者_如何学JAVAsetup() function doesn't display. I have no idea why. However, if I put a console.log statement immediately following the top line, for example, it does work:

;(function($) {
  console.log('hello world');

.....Can someone please tell me what I'm doing wrong?


Your call is incorrect:

<script type="text/javascript" src="myPlugin.js"></script>
<script type="text/javascript"> 
    $(document).ready(function(){
        $('ul').myPlugin();
    });
</script>


Ambrosia points out the issue you asked about, as your call was incorrect. Your .ready() didn't contain the function.

However, you might want to consider setting up your plugin a little differently. Right now no one can override your defaults on a global basis, and your use of .extend obscures what you are trying to do. This is how I would recommend setting up your plugin, but of course, everyone does it differently:

;(function($) {

  $.fn.myPlugin = function(options) {
     return this.each(function() {
       (new $.MyPlugin(this, options));
     });
  };

  $.MyPlugin = function(element, options) {     
     this.options = $.extend({}, $.MyPlugin.defaults, options); 

     this.setup = function(){
       console.log(this.helloText);
     };

     this.setup();         
  };

  $.MyPlugin.defaults = {                      
     helloText: "hello World"                      
  }; 

})(jQuery);

In addition to being easier to follow, someone can now override your options for all the calls to the plugin by using this:

$.MyPlugin.defaults.helloText = "Something Else";
$('ul').myplugin(); // Outputs 'Something Else' to the console

I have written a helper for jQuery Plugins called Starter for jQuery but there are tons of other great resources out there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜