knockout.js - data-bind text default value

2020-08-09 05:56发布

In knockout.js I have a very standard field that looks like this:

<label data-bind="text: JobTitle"></label>

What I'd like is to have a default value specified in here if the text value is null, for example "No Job Title Specified".

Is this possible to do in knockout.js?

Thanks.

7条回答
成全新的幸福
2楼-- · 2020-08-09 06:29

Even shorter than other code samples is the following:

ko.extenders.withDefault = function(target, defaultValue) {
    target.subscribe(function(input) {
        if(!input) target(defaultValue)
    });
    return target
};

With the initiation

ko.observable().extend({ withDefault: "some Default" })
查看更多
登录 后发表回答