javascript - In KnockoutJS, is there a specific order in which computed values must be declared? -
i javascript runtime error when run code below. uncaught typeerror: cannot read property 'name' of null
in dep3
when accessing self.dep2().name
.
the error goes away if move declaration of dep2
above of dep1
. bug in knockout or i'm doing wrong? seems me dep3
being recomputed result of dep1
changing before dep2
has been recomputed have expected knockout able handle scenario.
function viewmodel () { var self = this; self.root = ko.observable(null); self.dep1 = ko.computed(function () { return self.root() ? self.root().prop1 : null; }); self.dep2 = ko.computed(function () { return self.root() ? self.root().prop2 : null; }); self.dep3 = ko.computed(function () { if (self.dep1()) { return self.dep2().name; } }); } globalviewmodel = new viewmodel(); globalviewmodel.root({ prop1: {name: "thisispropone"}, prop2: {name: "thisisproptwo"} });
you right way dependencies evaluated. change root
trigger dep1
, dep2
re-evaluated, change dep1
triggers dep3
first.
in case, 1 option throttle dep3
like:
self.dep3 = ko.computed(function () { if (self.dep1()) { return self.dep2().name; } }).extend({ throttle: 1 });
otherwise, checkout michael best's deferred updates plugin here: https://github.com/mbest/knockout-deferred-updates, handle in more robust way throttling.
Comments
Post a Comment