Knockout JS - Array osservabile deve essere popolato dall'oggetto Dettaglio
-
15-11-2019 - |
Domanda
Ecco il violino http://jsfiddle.net/srinivasanvee/yyewj/2/
Ho una lista che ha categoria, prodotto, quantità come colonne, Ho la possibilità di aggiungere nuova categoria dal menu a discesa (Seleziona --Aggiungi nuova, opzione), Volevo popolare la categoria List ObservableArray dalla categoria Metodo di iscrizione (dal momento che il valore appena aggiunto deve essere applicato a tutte le file della rete), Non sono sicuro di come farlo, provato con $ root.categorylist.push (nome), ma senza fortuna
o abbiamo ancora un modo migliore di gestire questo scenario? Aiuto su questo molto apprezzato, grazie in anticipo.
Soluzione
Variables like $root
are only available within the bindings.
One way to make this work is to pass a reference to your root view model to your cartLine constructor.
Your cartLine would end up looking like:
var cartLine = function(data1, root) {
this.category = ko.observable(data1.category);
this.product = ko.observable(data1.product);
this.quantity = ko.observable(data1.quantity);
this.category.subscribe(function(newValue) {
if (newValue == "--Add New--") {
var name = prompt("Enter Table Name");
if (name == null) {
return false;
}
else {
root.categoryList.push(name);
}
}
});
};
Then, you just need to pass this
in as the second argument from your view model when creating a new cartLine. Sample here: http://jsfiddle.net/rniemeyer/kzZSH/
Otherwise, you could create your cartLine as you were and subscribe from your viewModel after getting a reference to the new line back.