knockout.js - Referencing observable from inline computed method -
am missing anything, or not possible declare computed "inline" property id_and_name below in first example?
function viewmodel(){ var self = this; // adding 'inline' won't work (exception functions doesn't exist): self.person = ko.observable({ id: ko.observable(), name: ko.observable(), id_and_name: ko.computed(function(){ return this.id() + this.name(); }, self.person) }); // works: self.person.id_and_name = ko.computed(function(){ return this.id() + this.name(); }, self.person); }
well, self.person undefined until after ko.observable call has returned. computed bootstrapped before that, bootstrapped @ moment when self.person still undefined. can check out in the computed source code file, pretty easy read actually.
here's 1 way @ that:
function viewmodel() { var self = this; self.person = "temp"; self.person = ko.observable({ id: ko.observable(), name: ko.observable(), id_and_name: ko.computed(function() { console.log(this); return this.id() + this.name(); }, self.person) }); } it'll log "temp" upon initializing, because that's self.person is @ time. cannot change this target computed read function after created.
so nope, want can't done. need second solution or proper view model constructor function*.
* top level viewmodel such constructor function. create inner constructor funciton person id , name properties, , new up, give id_and_name computed automatically have correct this bound.
Comments
Post a Comment