I am trying to turn div#sidebar into a sidebar in my app. My code looks like the one below.
$('#sidebar').userProfile();
jQuery.fn.userProfile = function() {
$.get('/users/profile', function(data){ $(this).html(data); });
};
It didnt work because, I found the this (inside the $.get function) here contexts to the get request and not $(‘#sidebar’). Then I tried something like below.
$('#sidebar').userProfile();
#This doesnot work
jQuery.fn.userProfile = function() {
var side_bar = null;
$.get('/users/profile', function(data){ side_bar = data; });
$(this).html(side_bar);
console.log(side_bar);
};
This doesnt work either. In firebug console I see Null which I am setting on top when I am declaring the variable.Atlast I made it work by changing my code to something like below by hardcoding the selector.
#This works, but I cannot turn any element to a sidebar which is sick.
jQuery.fn.userProfile = function() {
$.get('/users/profile', function(data){ $('#sidebar').html(data); });
};
But this is not I wanted because I wanted to turn any element to a sidebar. Where am I goin wrong or which is the correct way of doing it?
Since
thischanges with each context, it’s an often used technique to storethisin another variable at your earliest convenience to capture the right context.Your second example doesn’t work because the
.getcallback is executed asynchronously at an undefined later time (when the data comes back).