I am trying to create a plugin where I pass on handler functions for specific events. In the simple example below, I have two buttons. When I press button 1, its label should change to 'Button A', and when I press button 2, its label should change to 'Button B'.
However, what is happening is when I press button 1, the label changes to 'Button B'. I know this has something to do with the handler function closure in the loop, but I just can't figure out how to fix it.
<body>
<button class="btn1">Button 1</button>
<button class="btn2">Button 2</button>
</body>
Here's my jquery:
$(function() {
$("body").myplugin( {
helperFunctions : {
funcA : function( obj ) {
$(obj).text( "Button A" );
},
funcB : function( obj ) {
$(obj).text( "Button B" );
}
},
handlers : [
{
on : "click",
selector : ".btn1",
handlerFunc : function( funcs, obj ){
funcs.funcA( obj );
}
},
{
on : "click",
selector : ".btn2",
handlerFunc : function( funcs, obj ){
funcs.funcB( obj );
}
}
]
});
});
(function ($) {
$.fn.extend({
myplugin: function ( settings ) {
var $this = $(this);
function createHandlerFunction( func, obj ){
return func( settings.helperFunctions, obj ) ;
}
for( var handlerIdx in settings.handlers ){
var handler = settings.handlers[ handlerIdx ];
$this.on(
handler.on,
handler.selector,
function() {
return createHandlerFunction( handler.handlerFunc, this ) } );
}
}
});
})(jQuery);
Sorry if the example is a bit long. Here's http://jsfiddle.net/30nL07db/