JQuery Function Trouble

I’m having a problem getting this to work with return all the data at once from the each portion.

Can anyone see what I have done wrong?


$.fn.LoadMessages = function() {
	$.getJSON('/ajaxListMessages/4', function(data)
	{
		this.each(data, function(key, val) {
			$(area).append(data[key].login + data[key].message + '<br />');
		});
	});
}

$(document).ready(function() {
	$("#MSG").LoadMessages();
});

If I do it this way it works, but i dont want to do it this way because i have to specify the same thing twice!


$.fn.LoadMessages = function(varx) {
	$.getJSON('/ajaxListMessages/4', function(data)
	{
		$.each(data, function(key, val) {
			$(varx).append(data[key].login + data[key].message + '<br />');
		});
	});
}

$(document).ready(function() {
	$("#MSG").LoadMessages("#MSG");
});

It sounds like you’re wanting the .selector method.

Thanks for the reply PMW.

I read your post, that was an interesting function I haven’t played with. I then looked over some JQuery plugin development areas and found the culprit!

It has to do with “this” (not the same as $(this) ) – I assumed that the “this” of a function behaved differently than $(this) – okay now this is sounding really confusing…

Anyways, this being nested inside the “getJSON”, was applying to the JSON item, so I need a variable to maintain the DOM element inside it by creating a variable.

Solution:

$.fn.LoadMessages = function()
{
	var rootThis = this;
	$.getJSON('ajaxListMessages/5', function(data)
	{
		$.each(data, function(key, val) {
			rootThis.append(data[key].login + data[key].message + '<br />');
		});

		
	});

}