I am writing a jQuery plugin and it involves binding an event to window.scroll. The action taken within window.scroll depends on the settings passed in when the original intialization is called.
How do I access the data element, or this, inside a bound event?
(function($) {
var methods = {
init : function(options) {
return this.each(function() {
$(window).bind("scroll.myPlugin", methods.windowOnScroll);
});
},
windowOnScroll : function() {
var $this = $(this);
var data = $this.data("scrollingLoader");
if (data.something) {
// ...
}
}
})(jQuery);
jQuery provides a convenience function, $.proxy
, that does cross-browser function binding.
(function($) {
var methods = {
init : function(options) {
return this.each(function() {
$(window).bind("scroll.myPlugin", $.proxy(methods.windowOnScroll,methods));
});
},
windowOnScroll : function() {
var $this = $(this);
var data = $this.data("scrollingLoader");
if (data.something) {
// ...
}
}
})(jQuery);
The $.proxy function returns a function that will always execute the function passed in the first argument in the context of the second argument. http://api.jquery.com/jQuery.proxy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With