To bind a Element/Object to be available to jQuery.post callback (better way?)
I have this function in charge of making a ajax call, and based on the response, change a HTML El开发者_StackOverflow中文版ement
The thing is.. I need to know the know which element triggered the call when the callback happen. The way it is right now, seems to be working (have tested only in Chrome); but for some reason it does not appear for me being a 'jQuery way' of doing it.
function accept_order(e){
var target = $(e.currentTarget)
$.post('painel_restaurante/accept_order',
{
authenticity_token: j('[name=csrf-token]').attr('content'),
id: target.parents('tr').attr('data-order-id')
},
function(resp, status, xhr){
if(resp && resp.length && resp[0] == true ){
alert(xhr.element) // <-- attention here
}
},
'json'
).element = target // <-- and attention here
return false;
}
$('.action_button.accept').click( accept_order );
Is this a good way? Any suggestion for something better?
The same logic of this applies to .ajax and .get, I'd recommend to have this sort of example in the official API
EDIT+
Screenshot CLOSURE, where? <-- Chrome debugger FAIL. Actually, using console.log() would show the variable defined.This is the beauty of Javascript; you can simply access variable target
in the success function because of the closure.
精彩评论