rolodex
rolodex

Reputation: 530

Creating a jQuery callback function

I have problem understanding how to create a callback function which I can use to extend the options, as stated in this guide. Here's the excerpt of code that I want to use for callback;

var chart       =   {};
chart.data      =   $('.liselected').attr("data"); 
chart.command   =   $('.liselected').attr("cmd");
chart.option    =   "option"; // Category of event request
chart.sessionid =   docCookies.getItem("sessionid");
chart.ageType   =   selectedAgeType;
chart.showData  =   showUnderlyingData;

var action  =   function(result, status) {

    $('#thumbnails .error').remove();
    var chart_list  =   "";

    $.each(result, function(i, val){
        chart_list += //Custom HTML Output
    });

    $('#chart_view').html(chart_list);
};

$.post("jsoncommand", JSON.stringify(chart), action);

So that I can call using $("a").on("click", postcommand(eventrequest)), I tried creating a function like this;

$.fn.postcommand = function(){
    var settings = $.extend({
        item        :   {},
        data        :   $('.liselected').attr("data"),
        command     :   $('.liselected').attr("cmd"),
        option      :   "specify query",
        sessionid  :    docCookies.getItem("sessionid"),
        ageType     :   selectedAgeType,
        showData    :   showUnderlyingData,
    }, options );

    return //How do I make the output of HTML result is customizable?
};

But of course, my attempt is a failure. Spoon feeding is good, but you can always give me a hint and I'll try to explore on my own. Thanks!

Upvotes: 0

Views: 145

Answers (1)

meavo
meavo

Reputation: 1042

It might be a good idea to check out the jQuery plugin section: http://learn.jquery.com/plugins/advanced-plugin-concepts/. You could do something like this:

$.fn.postcommand = function (options) {

    // define some default values for your plugin
    var default = {
        callback: function () {}
    }

    // merge default settings,  with the ones given  
    var settings = $.extend( {}, defaults, options );

    return this.each(function() {
        var $this = $(this);
        $this.on('click', function(event) {
          settings.callback();
          event.preventDefault();
        });
    }
});

And then use your plugin on some links:

$('a.useCallback').postcommand();

Upvotes: 1

Related Questions