techie_28 techie_28 - 7 months ago 12
Javascript Question

Can not access element attributes after passing the reference jQuery

I have a HTML grid which has variable number of rows which has a datepicker in first column & an HTML button in 3rd column.

I need to get the reference of button & pass it around in functions(may be more then once) to call its click or access its attribute at various places.

var myButton = $(this).parents('tr').find('input[type=button]'); // accesing the button in a function


further I am passing this variable in an object to another JS function doSomething

doSomething.call(this, { 'btnRef': myButton[0] }, condition);


Inside the doSmething function I am saving this reference in a global JS object

unsavedObj['btnRef'] = arguments[0]['btnRef']; // I also tried jQuery(arguments[0]['btnRef'])


Problem occurs after I try to access an attribute via the global object

unsavedObj['btnRef'].attr('rel')
unsavedObj['btnRef'] // shows as undefined in console.


I can access attributes etc correctly inside the function where var myButton is getting the value also
jQuery(arguments[0]['btnRef'].attr('rel'))
returns the right result as well.
Is this the problem due to context?.

Sample code:

//this is the datepicker handler which fires on select of a date.


onSelect: function(d,i) {
var condition = false;
var myButton = $(this).closest('tr').find('input[type=button]');
var btnRel = myButton.attr('rel');
//some other vars

myButton.prop("disabled", false); //this works fine

if(jQuery(myButton).hasClass('xyz')){
if(changedFor !=''){
if(changedFor == btnRel){
condition = (changedFor == btnRel);
}
}
doSomething.call(this,{'btnRef':myButton},condition);//passing to the function doSomething
}
}


//doSomething function.
function doSomething(){
var thisObj = jQuery(this)
if(arguments[1]){
unsavedObj['btnRef'].triggerHandler('click',{'check':arguments[1]});
}else{
BootstrapDialog.show({ //this is a bootstrap dialogbox
title:'',
message:function(dialog){
var $content = "Are you sure?";
return '<div>' + $content + '</div>';
},
closable: false,
buttons: [{
label:'Change',
cssClass: 'btn',
action: function(dialogItself){
unsavedObj['btnRef'] = arguments[0]['btnRef'];
unsavedObj['context'] = thisObj;
changedFor = unsavedObj['btnRef'].attr('rel'); //does not work
unsavedObj['btnRef'].click(); //does not work
dialogItself.close();
}
},{
label:'Cancel',
cssClass:'btn',
action: function(dialogItself){
dialogItself.close();
}
}]
});
}
}


Im sorry for the poor formatting.

Thanks.

Answer

Sorry this problem was happening due to the limitation of closures to access the arguments object of outer function & here Bootstrap.show({..'s button definition was actually a closure. It was resolved by creating a copy of arguments.

Thanks all.