0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ducin
  • 25,621
  • 41
  • 157
  • 256

1 Answers1

2

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Only if the `xyz` variable value didn't change in between. To be safe OP could declare a variable `var _this=this` inside `bindMenuOptions`. +1 anyway. – Denys Séguret Apr 04 '13 at 19:53
  • @Benjamin - so if I use this proxy thing, `this` will be the same as `xyz` right? Could you please explain why the `xyz.get...` is nicer in your opinion? – ducin Apr 04 '13 at 19:56
  • By the way, can I do `$('#menu_outcome_list').bind('click', $.proxy(function(){...},this)` - or will I get the same error? – ducin Apr 04 '13 at 19:58
  • About the proxy thing, Yeah. There are plenty of examples in the jQuery API link in the answer. As for nicer option, using the keyword 'this' can be confusing in this sort of context. In JavaScript this is dynamically bound, can be manually set (with call or apply for example). You know exactly what xyz is, it is the object you are using. There is no ambiguity, which means less room for confusion also no additional function call, and less reliance on jQuery. BTW, the $.proxy method is available in a nicer version in JavaScript (but doesn't work in old IE) , http://mzl.la/RzcBaJ – Benjamin Gruenbaum Apr 04 '13 at 19:59
  • there's a typo though: should be `},xyz))` instead of `},xyz)` – ducin Apr 04 '13 at 20:03