In Javascript there are other patterns available to do this.
The first, and simplest, is akin to the ??
operator in C#:
function ViewModel(data) {
data = data || {};
this.Filename .observable(data.Filename || "");
}
The ||
operator will return the left operand unless it is falsy, then it'll fall back to the second argument. My example above will:
- Make sure
data
itself is "at least" an empty object (where .Filename
would be undefined);
- Make sure that the input to
ko.observable(...)
is "at least" the empty string.
A second option would be to use default options. An example that utilizes jQuery to merge input data and default options:
var defaultData = {
Filename: "enter-a-file" // could also be empty string of course!
};
function ViewModel(data) {
var dto = $.extend({}, defaultData, data);
this.Filename = ko.observable(dto.Filename);
}
This will "fold" data
into defaultData
, and fold that result into an empty, fresh object, making sure the dto
variable holds the merged result. The rest of your function can then safely assume a fully populated input variable.
The third and final option I'll mention is a remix of QBM5's answer, but I agree with the commenter's there that if you can use a pureComputed
(which, in your example, is perfectly fine), you probably should:
function ViewModel(data) {
var self = this;
data = data || {};
this.Filename = ko.observable(data.Filename);
this.FilenameText = ko.pureComputed(function() {
return self.Filename() || "";
});
}
PS. You didn't have the underlying issue you mention because you spell FileName
and Filename
with different capitalization on this
and data
respectively, didn't you? ;-)