Friday, 15 May 2015

Accessing this variable in jQuery plugin -



Accessing this variable in jQuery plugin -

i'm trying access "this" variable in plugin maintain getting error uncaught referenceerror: $self not defined. don't understand i'm doing wrong , first time i've tried building plugin way.

i've looked @ other plugins follow pattern i'm not seeing i'm missing compared theirs.

codes:

;(function($) { $.fn.videopagination = function(method) { // method calling logic if (methods[method] && method.charat(0) != '_') { homecoming methods[method].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { homecoming methods.init.apply(this, arguments); } else { $.error('method ' + method + ' not exist on jquery.videopagination'); } }; var methods = { init: function(options) { var o = $.extend({ per_page: 12, current_page: 1, src: '/videos.json' }, options || {}); var $self = $(this); $self.data('videopagination', o); methods.cover(); homecoming this; }, cover: function() { $self.find('article').each(function(i) { var video = $(this); settimeout(function() { video.fadeto(250, .2); }, 50*i); }); } }; })(window.jquery); $('.videos').videopagination();

the problem not utilize of this scoping of $self variable, see comments added below:

var methods = { init: function(options) { var o = $.extend({ per_page: 12, current_page: 1, src: '/videos.json' }, options || {}); var $self = $(this); //you defining $self variable here within scope of init function $self.data('videopagination', o); methods.cover(); homecoming this; }, cover: function() { $self.find('article').each(function(i) { // trying utilize here within scope of cover function. var video = $(this); settimeout(function() { video.fadeto(250, .2); }, 50*i); }); } };

instead need declare variable in larger scope can set , access in both locations:

(function($) { $.fn.videopagination = function(method) { // method calling logic if (methods[method] && method.charat(0) != '_') { homecoming methods[method].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { homecoming methods.init.apply(this, arguments); } else { $.error('method ' + method + ' not exist on jquery.videopagination'); } }; var $self; //notice $self declared outside of both functions. var methods = { init: function(options) { var o = $.extend({ per_page: 12, current_page: 1, src: '/videos.json' }, options || {}); $self = $(this); $self.data('videopagination', o); methods.cover(); homecoming this; }, cover: function() { $self.find('article').each(function(i) { var video = $(this); settimeout(function() { video.fadeto(250, .2); }, 50*i); }); } }; })(window.jquery); $('.videos').videopagination();

jquery

No comments:

Post a Comment