Try these:
$("#addon"+(parseInt(i))).click(heading.click_callback);
$("#addon"+(parseInt(i))).click(function(){heading.click_callback();});
Question
in writing an addon how do you pass an event based, optional function. I can do it by writing a name of the function manually as a string in the calling procedure, then adding it in the this.html() as an onclick="" in the string but that is naff. I would like to maturely pass the function as an optional argument and optionally add it as a click conditional event
the document
<div id="grid"></div>
<script>
$(function() {
$("#grid").myaddon({
"headings" : [
{
"title" : "hello",
"click_callback" : function(){
alert('hi');
}
},
{
"title" : "there"
}
]
});
});
</script>
and the addon itself
(function( $ ) {
var methods = {
init : function( options ) {
var defaults = {
"title": "text",
"click_callback": function() {}
}
for(var i=0; i<options.headings.length; i++) {
var heading = $.extend({},defaults,options.headings[i]);
this.html("<div id=\"addon"+(parseInt(i))+"\" >" + heading.title + "</div>");
if (typeof heading.click_callback == 'function') {
$("#addon"+(parseInt(i))).click( function() { heading.click_callback.call(this) }); //this doesn't work
$("#addon"+(parseInt(i))).click( function() { heading.click_callback.call() }); //this doesn't work
$("#addon"+(parseInt(i))).click( heading.click_callback.call()); //this doesn't work
$("#addon"+(parseInt(i))).click( eval(heading.click_callback.call())); //(in desperation) this doesn't work
//(edit)
$("#addon"+(parseInt(i))).click(heading.click_callback); //(!!thanks Robert Fricke!) thanks to the answer from Robert Fricke I know this works
//(/edit)
}
}
}
}
$.fn.myaddon = 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 on jQuery.myaddon' );
}
};
})( jQuery );
Solution
Try these:
$("#addon"+(parseInt(i))).click(heading.click_callback);
$("#addon"+(parseInt(i))).click(function(){heading.click_callback();});