views:

62

answers:

2

For some reason, the following bit of code isn't behaving as I would anticipate -- likely due to a misunderstanding on my end as to how it should behave.

var contentPane = widget.children("div.content").first();

var success = function (content) {
    return function (data, successCode, httpRequest) {
        content.innerHTML = data;
    };
}(contentPane); 

I've attached my debugger (well, Firebug anyway) and it looks like 'content' on the line content.innerHTML = data; is the Window object, when I should be the result of var contentPane = widget.children("div.content").first();, correct?

Note that if I set a breakpoint before the function, contentPane is indeed set to what I would expect (a jQuery object matching div.content). Whats going on here, what am I missing?

+2  A: 

This is what they added $.proxy() for in 1.4 :), like this:

var contentPane = widget.children("div.content").first();

var success = $.proxy(function (data, successCode, httpRequest) {
                       this.innerHTML = data;
              }, contentPane);

This just makes the closure declaration for the common case like you have much shorter, $.proxy(function, whatThisIs).


For the "what's wrong?" part...nothing, are you sure you're checking the right variable? this refers to window inside your function, but content is the jQuery object you want...you can see a quick test here: http://jsfiddle.net/vhcde/

Nick Craver
@downvoter - it helps to say *what* is incorrect, so it actually helps someone.
Nick Craver
+1  A: 

The problem may likely be your selector. The following works fine when run on this page

var contentPane = $("#header")[0];

var success = (function (content) {
    console.info(content);
    return function (data, successCode, httpRequest) {
        console.warn(content);
        content.innerHTML = data;
    };
})(contentPane); 

success("ohai");

* I've added parenthesis around the function definition for added clarity.

Justin Johnson
So what's the downvote for?
Justin Johnson