Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Undestroy' an object in Knockout

I keep track of deleted objects in an observableArray called 'Deletions'. I parse that array in the UI to create 'undo deletion' links, but I can't get this to work. The code is very straight-forward 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 Deletions observableArray. The only thing I need to do in the 'unremove' function, is setting the 'destroy' flag to false. But, I can't get that to work:

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

What's the correct way of doing this?

EDIT

I can't get this working for the nested FormElements. The structure is: my main ViewModel is called 'FormBuilder'. The FormBuilder has multiple Pages (those are ViewModels themselves) and each Page has multiple FormElements (see code snippet above).

I can 'undelete' those FormElements, but I have no clue how to force a refresh on them.

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 observableArray called Pages, each Page is a ViewModel;
  • Each Page has an observableArray called FormElements, each FormElement is a ViewModel;
  • FormBuilder has an observableArray called Deletions, each Deletion is a ViewModel and each Deletion contains an element, either a Page or a FormElement.

The problem: I use the function 'unremove' to set the 'destroy' property of the element (either Page or FormElement) to false. As you can see, I then call 'valueHasUpdated' on pages. But how do I call that on the observableArray formElements as contained by an individual Page?

like image 960
Sherlock Avatar asked Sep 17 '12 07:09

Sherlock


1 Answers

_destroy is not an observable. So, what you can do it set _destroy to false and then call valueHasMutated on the observableArray, so that any subscribers (the UI) knows that it may need to make updates.

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

like image 101
RP Niemeyer Avatar answered Oct 17 '22 03:10

RP Niemeyer