Reputation: 1390
I'm a jquery noobie so apologies if question is unclear. I've been trying to get my head around callbacks from the various posts, but am getting stuck on how it all fits together.
Essentially, I have currently 3 methods which make an ajax call and populate an element. An example of one function
function RetrieveUsers() {
$.mobile.pageLoading(false);
$.ajax({
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: args,
url: "Default.aspx/RetrieveUsers",
success: function (d) {
$("#userList").empty();
var html;
var rows = eval('(' + d.d + ')');
for (var o in rows) {
var row = rows[o];
html += '<li>' + row.name + '</li>';
}
$("#userList").html(html);
$.mobile.pageLoading(true);
},
error: function (x, t, e) {
alert(x.responseText);
}
});
What I would like to do is re-use the ajax call functionality and pass the row set back to the appropriate method which knows how to populate the desired element on the form.
function SearchUsers(searchText) {
var url = "Default.aspx/SearchUsers";
var parameterData = '{ "searchText": "' + searchText + '" }';
CallPageMethod(url, parameterData, DisplayUsers(userData));
}
function DisplayUsers(users)
{
//populate the element
var html;
for(var user in users)
{
html += '<li>' + user.userName + '</li>';
}
$('#userList').html(html);
$.mobile.pageLoading(true);
}
function CallPageMethod(url, paramterData, callbackFunctionWithArgs)
{
$.mobile.pageLoading();
$.ajax({
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: paramterData,
url: url,
success: function (d) {
var rows = eval('(' + d.d + ')');
callbackFunctionWithArgs(rows);
},
error: function (x, t, e) {
alert(x.responseText); //just use generic alert for now
}
}
and for instance my task search would now look like this:
function SearchTasks(searchType, searchText)
{
var url = "Default.aspx/SearchTasks";
var parameterData = '{ "searchType": "' + searchType + '", "searchText": "' + searchText + '" }';
CallPageMethod(url, parameterData, DisplayUsers(userData));
}
function DisplayTasks(tasks)
{
var html;
for(var task in tasks)
{
html += '<li>' + task.Status + ', ' + task.Description + '</li>';
}
$('#taskList').html(html);
$.mobile.pageLoading(true);
}
would anyone be able to help me understand how to wire this up?
thanks Matt
Upvotes: 1
Views: 338
Reputation: 10772
Well looks reasonable from a first read, one thing you need to remember though: if you are trying to pass a reference to a function you should not use ()
or pass arguments, as this will result instead in calling the function.
So,
CallPageMethod(url, parameterData, DisplayUsers(userData));
should probably be:
CallPageMethod(url, parameterData, DisplayUsers);
Upvotes: 1