0

I have this example block of code that keeps repeating so many times now.

$(function(loadDatabyClickA){
    $('button').live('click', function(){

        selectedAgeType   = $(this).attr('value');

        var x       =   {};

        x.data      =   $('a').attr("data"); //selected item in tree (.liselected)
        x.command   =   $('a').attr("cmd");
        x.option    =   "x";
        x.sessionid =   docCookies.getItem("sessionid");
        x.ageType   =   selectedAgeType;
        x.showData  =   showUnderlyingData;

        var action  =   function(result, status) {

            var x_list  =   "";

            $.each(result, function(i, val){
                x_list  += "<li><h3>"+val.xtitle+"</h3></li>";
            });

        $('#x_view').append(x_list);
        };

        $.post("jsoncommand", JSON.stringify(chart), action)
        .error(function(){
            alert('error');
        });

    })
})

How can I extract this block so I can access it from another function? Maybe like using .extend()? This block is used by other function like this:

$(function(loadDatabyClickB){
    $('button2').live('click', function(){

        selectedAgeType   =   $(this).attr('value');

        var y       =   {};

        y.data      =   $('a').attr("data"); //selected item in tree (.liselected)
        y.command   =   $('a').attr("cmd");
        y.option    =   "y";
        y.sessionid =   docCookies.getItem("sessionid");
        y.ageType   =   selectedAgeType;
        y.showData  =   showUnderlyingData;

        var action  =   function(result, status) {

            var y_list  =   "";

            $.each(result, function(i, val){
                y_list  += "<li><h3>"+val.ytitle+"</h3></li>";
            });

            $('#y_view').append(y_list);
        };

        $.post("jsoncommand", JSON.stringify(y), action)
        .error(function(){
            alert('error');
        });

    })
})

You guys can just show me a hint of how to do this because I don't have a clue. I will simplify it myself. Thanks in advance for your help!

3 Answers 3

1

Create a function to generate a click handler based on the "view" that you pass in.

function getButtonClickHandler(view) {
    return function () {
        selectedAgeType   =   $(this).attr('value');
        var y       =   {};
        y.data      =   $('a').attr("data"); //selected item in tree (.liselected)
        y.command   =   $('a').attr("cmd");
        y.option    =   view;
        y.sessionid =   docCookies.getItem("sessionid");
        y.ageType   =   selectedAgeType;
        y.showData  =   showUnderlyingData;
        var action  =   function(result, status) {
            var y_list  =   "";
            $.each(result, function(i, val){
                y_list  += "<li><h3>" + val[view + 'title'] + "</h3></li>";
            });
            $('#' + view + '_view').append(y_list);
        };
        $.post("jsoncommand", JSON.stringify(y), action)
        .error(function(){
            alert('error');
        });
    }
}

$(function () {
    $('button').on('click', getButtonClickHandler('y'));
    $('button2').on('click', getButtonClickHandler('x'));
});
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps, using .on() would be better? .live() has been deprecated in later versions of jQuery ;)
You need to differenciate between different properties of the val as well. So, just change val.ytitle to val[view+'title'] in your code
What if I want to remove ageType and showData? If y_list is using different DOM such as <a>, how do extend the parameter?
0

create your own class and call your function from your class

var youClass = {
        functionName : function() {
            selectedAgeType   = $(this).attr('value');

        var x       =   {};

        x.data      =   $('a').attr("data"); //selected item in tree (.liselected)
        x.command   =   $('a').attr("cmd");
        x.option    =   "x";
        x.sessionid =   docCookies.getItem("sessionid");
        x.ageType   =   selectedAgeType;
        x.showData  =   showUnderlyingData;

        var action  =   function(result, status) {

            var x_list  =   "";

            $.each(result, function(i, val){
                x_list  += "<li><h3>"+val.xtitle+"</h3></li>";
            });

        $('#x_view').append(x_list);
        };

        $.post("jsoncommand", JSON.stringify(chart), action)
        .error(function(){
            alert('error');
        });
        }
    }



//call your function
    $('button').live('click', function(){

        youClass.functionName(parameter);

    })

2 Comments

this wont work since he is using different selectors in the event handler $('#y_view') vs $('#x_view')
How do I define what parameter to use?
0

Try this:

window.bindClick = function(selector, option, view) {
    view = view || '#' + option + '_view';
    $(document).on('click', selector, function(){

        selectedAgeType   = $(this).attr('value');

        var x       =   {};

        x.data      =   $('a').attr("data"); //selected item in tree (.liselected)
        x.command   =   $('a').attr("cmd");
        x.option    =   option;
        x.sessionid =   docCookies.getItem("sessionid");
        x.ageType   =   selectedAgeType;
        x.showData  =   showUnderlyingData;

        var action  =   function(result, status) {

            var list  =   "";

            $.each(result, function(i, val){
                list  += "<li><h3>"+val[option+'title']+"</h3></li>";
            });

            $(view).append(list);
        };

        $.post("jsoncommand", JSON.stringify(chart), action)
        .error(function(){
            alert('error');
        });

    })
})

and from any place in your code:

bindClick('#button', 'x', '#x_view');
bindClick('#button2', 'y', '#y_view');

or just

bindClick('#button, #button2', 'x');

4 Comments

this wont work since he is using different selectors in the event handler $('#y_view') vs $('#x_view')
with event delegation you could just do bindClick('#button,#button2'); that way you only bind one handler instead of two
What if for example, I would like to remove ageType and showData for another event?
@rolodex than you just need to add another boolean parameter to bindClick and surround code that sets showData and ageType inside the function with if that uses that parameter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.