views:

1730

answers:

3

JavaScript code I'm starting with:

function doSomething(url) {  
  $.ajax({ type: "GET",  
           url: url,  
           dataType: "xml",  
       success: rssToTarget  
       });  
}

Pattern I would like to use:

//where elem is the target that should receive new items via DOM (appendChild)
function doSomething(url, elem) {
    $.ajax({ type: "GET",
         url: url,
         dataType: "xml",
     success: rssToTarget(elem)
       });
}

I don't think I can get the callback to work this way, right? What is the proper pattern? I don't want to use global variables necessarily to temporarily hold the elem or elem name.

+8  A: 

Like this...

function doSomething(url, elem) {
  $.ajax({
     type: "GET",
     url: url,
     dataType: "xml",
     success: function(xml) {
       rssToTarget(xml, elem);
     }
  });
}

Answer to your comment: Does use of anonymous functions affect performance?

Josh Stodola
aha +1. Do you pay any performance price for creating anon functions everywhere?
tyndall
And I guess it would really be.... success: function(xml) { rssToTarget(xml, elem); }
tyndall
If you concur can you update the answer? Thanks Josh
tyndall
I've updated the answer
Josh Stodola
+2  A: 

The pattern you'd like to use could work if you create a closure inside your rssToTarget function:

function rssToTarget(element) {
  return function (xmlData) {
    // work with element and the data returned from the server
  }
}

function doSomething(url, elem) {
    $.ajax({ type: "GET",
         url: url,
         dataType: "xml",
         success: rssToTarget(elem)
       });
}

When rssToTarget(elem) is executed, the element parameter is stored in the closure, and the callback function is returned, waiting to be executed.

CMS
cool approach +1
tyndall
-1 You cant set success to a function that returns a function.
Josh Stodola
I forgot to add " but requires a parameter"
Josh Stodola
of course you can return a function check the code running! http://jsbin.com/anepo/edit
CMS
The returned anonymous function has an input parameter... JavaScript functional capabilities allows you to do that and more with functions...
CMS
A: 

How can i append dynamic values in the URL attribute in $.ajax() or $.post().

Doing something like $.post("somepage.cfm?somevalue",blablablab,blablabla);

is not working. Can anyone put me on right track please.

Thanks CF

You should post a separate question, but you can just use JS concatenation such as"somepage.cfm?"+varContainingSomeValue+...
raptors