I have a object creationParams
declared outside of all my functions. The object will be manipulated throughout the functions. However, I'm having an issue in pushing an Object to creationParams
's Property with an Array
datatype.
Code
var creationParams = {};
creationParams.Project = {};
creationParams.Project.Workplaces = [];
$(#foo).click(function() { //this is the function that runs before someid
//input validations here...
creationParams.Org = $('#SelectedOrg').val();
creationParams.Token = '';
});
$('#someid').click(function () {
$(this).attr('href', '#');
function isWpExisting(o) {
for (var cntr = 0; cntr < creationParams.Project.Workplaces; cntr++) {
if (creationParams.Project.Workplaces[cntr].Name.toUpperCase() === o) {
return true;
}
}
return false;
}
if ($('#wp-name').val() === '') {
$('#wp-name').addClass("error-field").attr("data-original-title", "Please enter Workplace Name");
$(this).attr('href', '#');
}
else if (isWpExisting($('#wp-name').val().toUpperCase()) === true && !$('#wp-wpcreate').attr('wp-edit')) {
$('#wp-name').addClass("error-field").attr("data-original-title", "This Workplace is already existing");
$(this).attr('href', '#');
}
else {
$(this).attr('href', '#divWp-one');
$('#wp-name').removeClass("error-field").removeAttr("data-original-title");
var workPlace= {};
workPlace.Name = $('#wp-name').val();
workPlace.Description = $('#wp-description').val();
if ($('#wp-wpcreate').attr('wp-edit')) {
for (var t = 0; t < creationParams.Project.Workplaces.length; t++) {
if (creationParams.Project.Workplaces[t].Name === $('#wp-wpcreate').attr('wp-edit')) {
creationParams.Project.Workplaces[t] = workPlace;
$('#wp-wpcreate').attr('wp-edit', '');
}
}
}
else {
creationParams.Project.Workplaces.push(workPlace);
}
}
});
//
...some more functions here
//
Im getting an error of "Cannot read property 'push' of undefined". I just want my object to be pushed to the Array. I have tried making another array and pushing into it and it works.
Update: I tried console.log(creationParams.Project.Workplaces);
and gave me undefined
.
Update 2: I got it working by moving the complete initialization of the creationParams.Project.Workplaces
in the #foo
function. I wonder why though, what is the difference of initializing it in a different place?
Questions
- Why is it behaving like this?
How can I make it work?Fixed (see Update 2)