"Undestroy" knockout facility

I track deleted objects in an observable array called "Deletes". I am parsing this array in the user interface to create “undo delete” links, but I cannot get this to work. The code is very simple and looks like this:

this.removePage = function(page){ self.formBuilder.pages.destroy(page); var newDeletion = new Deletion(); newDeletion.element(page); self.deletions.push(newDeletion); } this.removeFormElement = function(element){ self.formElements.destroy(element); var newDeletion = new Deletion(); newDeletion.element(element); builder.deletions.push(newDeletion); } var Deletion = function(){ var self = this; this.element = ko.observable(); }; 

Note that different types of elements can be added to the observed array of Deletsions. The only thing I need to do in the unremove function is set the destroy flag to false. But I can't get this to work:

 this.unremovePage = function(deletion){ deletion.element()._destroy(false); } 

What is the right way to do this?

EDIT

I cannot get this to work for nested FormElements. Structure: my main ViewModel is called FormBuilder. FormBuilder has several pages (these are ViewModels themselves), and each page has several FormElements (see code snippet above).

I can “restore” those FormElements, but I don’t know how to force them to be updated.

 this.unremove = function(deletion){ //console.log(deletion.element); deletion.element()._destroy = false; self.deletions.remove(deletion); self.formBuilder.pages.valueHasMutated(); // works deletion.element().valueHasMutated(); // this doesn't work self.formBuilder.pages.indexOf(deletion.element()).valueHasMutated(); // neither does this self.deletions.valueHasMutated(); // works }; 
  • FormBuilder is the main ViewModel;
  • FormBuilder has an observable array called pages, each page is a ViewModel;
  • Each page has an observable array called FormElements, each FormElement is a ViewModel;
  • FormBuilder has an observable array called Deletions, each Deletion is a ViewModel, and each Deletion contains an element, either a page, or a FormElement.

Problem: I use the "unremove" function to set the destroy property of an element (either page or FormElement) to false. As you can see, I call "valueHasUpdated" on the pages. But how can I call this an observable array of formElements contained in a separate page?

+4
source share
1 answer

_destroy not observable. So what you can do is set the _destroy parameter to false, and then call valueHasMutated in the observable array so that all subscribers (user interface) know that updates may need to be made.

So you want deletion.element()._destroy = false; and then call self.deletions.valueHasMutated() .

+7
source

Source: https://habr.com/ru/post/1434547/


All Articles