So, I’m writing my first plugin. I’m using the advice on the jQuery website, so my plugin setup looks something like this:
(function( $ ){
var methods = {
init : function( options ) {
var $this = $(this);
// do some code.
// Add an element
$this.append('<select id="test"><option value="yes">Yes</option>' +
'<option value="no">No</option></select>');
// Bind the change handler (chose '.on' after reading the documentation for '.delegate')
$this.on('change', '#test', methods['handler'].call($this, $('#test').val()));
},
handler : function( content ) {
alert ('You chose: ' + content);
}
};
$.fn.testbed = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist' );
}
};
})( jQuery );
I know that the handler itself is working, because I can substitute
function(){ alert ("You did it!");}
for the function call, and it works.
But, the way I’m calling the function now doesn’t work. It’s how I call other functions from within other methods, but it doesn’t work with a handler.
So, my questions are: (1) How do I make it call the function? and (2) is this the best place to set up the handler?
An id should be unique in the page. Having several elements with the same id will give you a different element from what you think when you try to access it. Don’t use an id at all, use
thisin the callback to get the right element.There is no reason to create a delegate when you are creating one for each event. Bind the event on the select element directly.
The handler for an event should be a function, not the result of a function call.