I have a computed property on my model which is just splitting a comma separated string into an array, and I want to be able to utilize the “checked” binding’s special array feature to write changes back through the computed property.
Everything works great for reading the computed property, but as soon as I check one of the checkboxes I get errors about some function not supporting splice (if I uncheck) or not supporting push (if I check).
> Uncaught TypeError: Object function
> h(){if(0<arguments.length)return"function"===typeof
> v?v.apply(d,arguments):j(Error("Cannot write a value to a ko.computed
> unless you specify a 'write' option. If you wish to read the current
> value, don't pass any parameters.")),this;n||g();b.r.Wa(h);return l}
> has no method 'splice' knockout-min.js:60 (anonymous function)
I created a quick sample on jsfiddle to illustrate what’s going on. http://jsfiddle.net/Y6tXw/
var MyModel = function() {
this.src = ko.observable("one,two");
this.comp = ko.computed({
read: function() {
return (this.src() || "").split(",");
},
write: function(value) {
var csvs = (value || []).join(",");
this.src(csvs);
},
owner: this
});
};
var model = new MyModel();
ko.applyBindings(model);
It never calls my write function. It seems like it’s crashing in the binding. What am I doing wrong?
comp in the above case in an computed, not an array. I have modified your code. I have used subscribe to listen to change notifications raised by comp and re-calculate the value of sec