Issue with calling publicly exposed method from event handler in jQuery plugin -


i keep getting error cannot call method 'changebackgroundcolor' of undefined. have click event set call public method within plugin. when method called programmatically works, if click element error.

my plugin html structure so:

<div class="container">     <div id="square"></div> </div> 

snipped plugin:

this.changebackgroundcolor = function() {   $('#square').css('background','red');  };  //note "this" .container bind click event child square     $('#square', this).bind('click', function () {         //error        changebackgroundcolor();      }); 

if call $('.container').myplugin().changebackgroundcolor(); works. if call changebackgroundcolor click event function can't find changebackground function.

link jsfiddle here

note: i'm using jquery 1.10.1

your "this" no longer same when you're inside function. mind you, jquery object not persistent, they're reflections on collections of htmlelements. consider storing event inside of .data or like.

if call $(".foo") twice in row, have 2 different objects, though reference same htmlelements.

but fix error this:

this.changebackgroundcolor = function() {     $('#square').css('background','red');  };  var _this = this; $('#square', this).bind('click', function () {     _this.changebackgroundcolor();  }); 

but issue pattern :)

you may want consider doing this:

var events = {     changebackgroundcolor: function() {         square.css('background','red');      },     changeitmore: function() {         square.css('background','purple');      } };  var square = $('#square', this).bind('click', function () {     events.changebackgroundcolor();  });  square.data("myevents", events); 

now other code, can do:

var theobject = $(".foo", container).yourplugin(); var yourevents = theobject.data("myevents"); yourevents.changebackgroundcolor(); 

another common pattern custom events, like:

function changebackgroundcolor() {     square.css('background','red');  }  var square = $('#square', this).bind('click', function () {     changebackgroundcolor();  }).bind("changebackgroundcolor", function() {     changebackgroundcolor();  }); 

now can trigger with:

$(".foo", container).yourplugin().trigger("changebackgroundcolor"); 

another common pattern accept, else maynot, have plugin return object that's not jquery object, , keep reference around. i'm a'ok :)


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -