jquery - Call a function within a function to init -


;(function ($, w, d, config, undefined) { $.fn.pluginname = function ( options, config ) {     var pluginname = this;     var defaults = {         //defaults     };     var settings = $.extend({}, defaults, options);      var methods = {         init :  function ( settings, options ) {             //init stuff here         }     } }) })(jquery, window, document)  // html looks <script> $('.item').pluginname({ methods : 'init' }); </script> 

i'm new plugin development, , objects in general, i'm trying learn in deep end without swimmies. :)

basically, want initialize plugin calling "init" function within methods variable. plugin's name "pluginname".

i having trouble calling "init" fn because lives within variable named "methods".

also, take 1 step further, need collect "item" classes on page , set inside data variable. in init function have following:

return this.each(function(){      var $this       = $(this),     data        = $this.data('pluginname');      if ( ! data ) {         $(this).data('pluginname', {         target : $this         });      } }).bind(this); 

the above returns "this.each not function"

any appreciated! lot!!

to make don't have pass in object method calls, use format:

(function($) {     function dosomething() {         // callable in plugin's context (i think)     }      var methods = {         init: function (options) {             // whatever init!             dosomething();         },          anothermethod: function (options) {             // other method             dosomething();         }     };      $.fn.pollserver = function(method) {         var args = arguments;         var argss = array.prototype.slice.call(args, 1);          return this.each(function () {             $this = $(this);             if (methods[method]) {                 methods[method].apply($this, argss);             }             else if (typeof method === "object" || !method) {                 methods.init.apply($this, args);             }             else {                 $.error("method " + method + " not exist on jquery.pollserver");             }         });     }; })(jquery); 

and access like:

$("#div").pollserver({}); $("#div").pollserver("init", {}); // same above line  $("#div").pollserver("anothermethod", {}); 

everything inside of return this.each() determines method call, , set "this" variable jquery element selected. passes additional arguments methods.

hope helps!


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -