knockout.js - knockoutjs child object trigger change in parent computed -
is there easier way parent object's 'subscribe' fire changes of lower level observables?
the following code , sample fiddle working, requires me duplicate masteroptions in optionset. smaller version manageable, masteroptions set can become quite large make maintenance of both masteroptions , optionset difficult , error-prone.
sample jsfiddle found here: fiddle
html:
<div> setting1a: <input data-bind="value: masteroptions.group1.setting1a" /><br /> setting1b: <input data-bind="value: masteroptions.group1.setting1b" /><br /> setting2a: <input data-bind="value: masteroptions.group2.setting2a" /><br /> setting2b: <input data-bind="value: masteroptions.group2.setting2b" /><br /> <br /> span1: <span data-bind="text: ko.tojson(optionset)"></span><br/> <br /> span2: <span id="myspan"></span> </div>
script:
var masteroptions = { group1: { setting1a: ko.observable("value1a"), setting1b: ko.observable("value1b") }, group2: { setting2a: ko.observable("value2a"), setting2b: ko.observable("value2b") } }; var optionset = ko.computed(function () { return { group1: { setting1a: masteroptions.group1.setting1a(), setting1b: masteroptions.group1.setting1b() }, group2: { setting2a: masteroptions.group2.setting2a(), setting2b: masteroptions.group2.setting2b() } }; }); optionset.subscribe(function () { //alert("make magic happen."); $("#myspan").html($("#myspan").html() + "more magic. "); }); var viewmodel = function () { return { masteroptions: masteroptions, optionset: optionset }; }; ko.applybindings(new viewmodel());
i rather not have recreate masteroptions optionset, don't see how can have single subscribe fire when of lower level observables change.
calling ko.tojs on masteroptions inside computed trick:
var optionset = ko.computed(function () { return ko.tojs(masteroptions); });
this creates dependency on every observable in structure. observables added included dependencies.
however if want subscribe directly masteroptions and/or need more flexibility might consider using handy little plugin wrote myself pretty same purposes:
Comments
Post a Comment