-
Notifications
You must be signed in to change notification settings - Fork 7
Description
I think the following might be a useful addition to our documentation:
The difference between lastSetValue and resolve
Summary: getters maintain both a lastSetValue and a getterValue. These are used for different parts of write and read functionality.
Getters like the following often confuse people:
VM = DefineMap.extend({
todoId: "number",
todo: {
get(lastSetValue, resolve) {
console.log("re-calculating", lastSetValue);
if(lastSetValue){
return lastSetValue;
}
Todo.get({id: this.todoId}).then(resolve);
}
}
});
vm = new VM({id: 5});It's important to understand that a property like todo actually houses two distinct values:
- lastSetValue - The
VALUEthat was last set likevm.todo = VALUE - getterValue - The value that was last returned by the
getfunction or passed toresolve(). This is the result of reading the property like:vm.todo.
It's important to understand that calling resolve() with a value will not set lastSetValue. Instead, calling resolve() only changes the getterValue.
Lets see how this plays out with an example. The following sets todoId and binds to todo. When todoId changes, a different todo instance can be read:
vm.on("todo", function(){});
// logs: re-calculating undefined
// ONCE THE PROMISE RESOLVES
vm.todo //-> Todo{id:5}
vm.todoId = 6
// logs: re-calculating undefined
// ONCE THE PROMISE RESOLVES AGAIN
vm.todo //-> Todo{id:6}Now, once todo is set, given the get above, vm.todo's getterValue will match lastSetValue even as todoId changes:
vm.todo = "HELLO THERE";
// logs: re-calculating "HELLO THERE"
vm.todo //-> "HELLO THERE"
vm.todoId = 7;
// logs: re-calculating "HELLO THERE"
vm.todo //-> "HELLO THERE"vm.todo's __getterValue__ will match __lastSetValue__ even as todoId` changes, unless lastSetValue is set to false:
vm.todo = false;
// logs: re-calculating false
// ONCE THE PROMISE RESOLVES AGAIN
vm.todo //-> Todo{id:6}