Javascript Array Concat not working. Why?
So I've created this jqueryui widget. Its creates a div that I can stream errors into. The widget code looks like this:
$.widget('ui.miniErrorLog', {
logStart: "<ul>", // these next 4 elements are actually a bunch more complicated.
logEnd: "</ul>",
errStart: "<li>",
errEnd: "</li>",
content: "",
refs: [],
_create: function() { $(this.element).addClass( "ui-state-error" ).hide(); },
clear: function() {
this.content = "";
for ( var i in this.refs )
$( this.refs[i] ).removeClass( "ui-state-error" );
this.refs = [];
$(this.element).empty().hide();
},
addError: function( msg, ref ) {
this.content += this.errStart + msg + this.errEnd;
if ( ref ) {
if ( ref instanceof Array )
this.refs.concat( ref );
else
this.refs.push( ref );
for ( var i in this.refs )
$( this.refs[i] ).addClass( "ui-state-error" );
}
$(this.element).html( this.logStart + this.content + this.logEnd ).show();
},
hasError: function()
{
if ( this.refs.length )
return true;
return false;
},
});
I can add error messages into it, and references to page elements that is will put into an error state. I use it to validate dialogs. In the "addError" method I can pass in a single id, or an array of ids, like this:
$( "#registerDialogError" ).miniErrorLog(
'addError',
"Your passwords don't match.",
[ "#registerDialogPassword1", "#registerDialogPassword2" ] );
But when I pass in an array of id's it doesn't work. The problem is in the following lines (i think):
if ( ref instanceof Array )
this.refs.concat( ref );
else
this.refs.push( ref );
Why doesn't that concat work. this.refs and ref are both arrays. So why doesn't the concat work?
Bonus: am I doing anything else dumb in this widget? It's my first one.
The concat method doesn't change the original array, you need to reassign it.
if ( ref instanceof Array )
this.refs = this.refs.concat( ref );
else
this.refs.push( ref );
Here is the reason why:
Definition and Usage
The concat() method is used to join two or more arrays.
This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.
You need to assign the result of the concatenation back in the array that you have.