knockout.mapping
knockout.mapping copied to clipboard
With knockout.js debug version, ko.isComputed and ko.isWriteableObservable doesn't work on create callbacks
Since withProxyDependentObservable replaces ko.dependentObservable, ko.isComputed and ko.isWriteableObservable doesn't work on create callbacks when using ko.js (DEBUG VERSION).
On theese fiddles, I test on a create ko.isComputable. On compiled ko.js version, ir alerts YES, and on debug version it alerts NO:
Here is a fiddle with debug version: http://jsfiddle.net/rZLh7/5/
An here is a fiddle with compiled version: http://jsfiddle.net/dmY8P/
¿Does anybody knows why it works this way? I use the knockoutjs debug version to develop so I can track errors easily on my code.
I'm not sure why you are creating a computed within a create callback like that, but regardless, a computed will only get evaluated and initialized after mapping is complete. This is to prevent circular references.
I have updated your fiddle to illustrate how you'd use it within a create callback: http://jsfiddle.net/rZLh7/6/
Hi Roy. The fiddle I posted was just an example. I use to call constructors on create callbacks, and sometimes I need to use ko.isComputed on those constructors.
I am also running into a problem with ko.isWriteableObservable not returning true for ko.computed observables during mapping.
I also see this issue was reported as https://github.com/SteveSanderson/knockout/issues/580.
Unfortunately, I cannot get jsfiddle.net to work with the mapping plugin, but here is an example. The expected behavior is that the alert should state "John Smith - name can be changed", however instead it states "John Smith - name cannot be changed". Like lisandropuzzolo I am calling a constructor during the mapping to create the view model and within that constructor ko.isWriteableObservable does not function as expected.
function PersonViewModel(options) {
this.name = ko.isObservable(options.name) ? options.name : ko.observable(options.name);
this.canEditName = ko.isWriteableObservable(this.name);
}
var personMapping = {
create: function (options) {
var person = options.data,
name = ko.computed({
read: function () { return person.firstName + ' ' + person.lastName; },
write: function (value) { /* NYI */ },
});
return new PersonViewModel({ name: name });
}
};
var person = ko.mapping.fromJS({
firstName: 'John',
lastName: 'Smith'
}, personMapping);
alert(person.name() + " - name " + (person.canEditName ? "can" : "cannot") + " be changed");
Ditto here. ko.isComputed is incorrectly returning false for me, even after the call to ko.mapping.fromJS returns. The issue for me seems to not be restricted to just within create callbacks. I will see about posting a distilled fiddle.
For the moment, now, I am kludging a workaround that looks like "if(someObservable.isActive)"