ObservableArray.RemoveAll () empties the contagioned objects in another variable

In my KnockoutJS view model logic, I have an observable array of currently displayed objects (project view models): self.currentProjects . Depending on the element filter setting (the user selects project types dynamically) self.currentProjects contains different objects to which the interface is bound.

At some point, when I need to load various projects into a view, I need to clear the current projects and put different models into it. I do this by calling self.currentProjects.removeAll(); The problem is when I call it, another observable array of self.ProjectModels , which should contain a reference to the same set of models, also seems empty. How do I manage objects in an observable array, so removing from one array does not cause the other to become empty.

Here is the code related to the manipulation:

  //Another menu item is selected self.selectItem = function(newId) { self.selectedItemId(newId); self.currentProjects.removeAll(); //This is the point where self.ProjectModels also looses model references var someProjectsLoaded = false; jQuery.each(self.projectModels, function (i, val) { if (val.type == self.selectedItemId()) { self.currentProjects(val.models); var projectsPerPage = parseInt($('#ProjectsPerPage').val(), "10"); self.page(val.models.length / projectsPerPage); someProjectsLoaded = true; } }); if (!someProjectsLoaded) { self.page(1); self.LoadMoreProjects(); } }; self.LoadMoreProjects = function() { var getProjectsUrl = $("#GetNextProjectsUrl").val(); $.ajax({ url: getProjectsUrl, data: { page: parseInt(self.page(), "10"), type: self.selectedItemId() }, beforeSend: function () { //$("#ajaxload").show(); }, success: function (result) { var newlyAddedModelsArray = jQuery.map(result, function (val, i) { var vm = new ProjectViewModel(val, self); self.currentProjects.push(vm); return vm; }); self.page(parseInt(self.page(), "10") + 1); var typeAlreadyInChache = false; jQuery.each(self.projectModels, function (i, val) { if(val.type == self.selectedItemId()) { val.models = val.models.concat(newlyAddedModelsArray); //HERE IS WHERE I SUSPECT A COPY BE REFERENCE TAKES PLACE typeAlreadyInChache = true; } }); if(!typeAlreadyInChache) { self.projectModels.push({ type: self.selectedItemId(), models: newlyAddedModelsArray }); } }, error: function () { $("#error").show(); } }); }; 
+4
source share
1 answer

A removeAll call empties the underlying array, and your two observables seem to have a reference to the same array.

An easy choice is to set currentProjects to an empty array, rather than calling removeAll .

 self.currentProjects([]); 

Now the original array will remain as it was.

+11
source

All Articles