jquery bind context mismatch

129 views Asked by At

I've got a HTML menu option, which I bind a click handler in jQuery:

var xyz = {
    getMainContainerSelector: function () {
        return '.container#main';
    },
    bindMenuOptions: function () {
        $('#menu_outcome_list').bind('click', function() {
            // inject template
            $(this.getMainContainerSelector()).html(ich.outcomeListTemplate({}));
            // load datatable
            $('#outcomes').dataTable({
                "bServerSide": true,
                'sPaginationType': 'bootstrap',
                "sAjaxSource": '../php/client/json.php?type=outcomes'
            });
        });
    },
    ...
}

I've got a problem with the following line:

$(this.getMainContainerSelector()).html(ich.outcomeListTemplate({}));

and I guess it's a context problem. I mean, inside the bind function, this is not xyz anymore, but the ('#menu_outcome_list') HTML element. What I want to do is just to call the xyz's method from inside the bind function.

1

There are 1 answers

5
Benjamin Gruenbaum On BEST ANSWER

You still have closure access to it in the methods you define in xyz.

You can just call xyx.getMainContainerSelector();

If you want a jQueryish solution, jQuery has a jQuery.proxy() function that binds context:

$('#menu_outcome_list').bind('click', $.proxy(function(){
    //rest of your code
},xyz)})

I think the first option is nicer though.