javascript - How to assign a KnockoutJs observable to another observable? -
i have model defined as:
var testmodel = function () { var self = this; self.item = ko.mapping.fromjs(new item()); self.itemlist = ko.observablearray(); }; var model = new testmodel(); ko.applybindings(model);
after ajax call fill array with:
ko.mapping.fromjs(data, {}, model.itemlist);
the array displayed in screen , when user selects item, modal dialog opened edit item. same modal dialog can opened add new item. modal has data-bind="with: item"
, can this:
function add() { ko.mapping.fromjs(new item(), {}, model.commission); //empty object $('#dialog').dialog('open'); }; function saveadd() { //clone properties... model.itemlist.push(ko.mapping.fromjs(ko.mapping.tojs(model.item))); } function edit(i) { //clone properties! ko.mapping.fromjs(ko.mapping.fromjs(ko.mapping.tojs(model.itemlist()[i])), {}, model.item); $('#dialog').dialog('open'); } function saveedit(i) { //clone properties!!!! model.itemlist()[i] = ko.mapping.fromjs(ko.mapping.tojs(model.item)); }
i want avoid cloning properties every time need assign values of 1 observable one. understand if manage tell knockout model.item is model.itemlist()[i]
, objects references should make sure changes in ui reflect directly observablearray item, cannot assing model.item = model.itemlist()[i];
because breaks binding between original model.item
object , view [*1].
is there way assign observable observable that's binded view, , maintain references?
failing that, better way this? basicaly page store list of items in observablearray , add/edit in piece of html.
edit: explanation [*1]
i cannot find stackoverflow question explained, this:
when ko.applybindings(model);
, observable objects inside model
binded view. @ point object referenced model.item
binded, if model.item = model.itemlist()[i];
new object being referenced model.item
not binded anything. original object (in memory) still 1 binded view, there no references now.
if make model.item observable, mapped object inside of it, can set observable's contents new item. reference observable made knockout remains intact because you're updating contents , not property itself.
var testmodel = function () { var self = this; self.item = ko.observable(ko.mapping.fromjs(new item())); self.itemlist = ko.observablearray(); }; ... model.item(model.itemlist()[i]);
Comments
Post a Comment