Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?

These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):

<input type="text" readonly="readonly" disabled="disabled" value="foo" />

However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):

<input type="text" value="foo" />

Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:

<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" />

Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
506 views
Welcome To Ask or Share your Answers For Others

1 Answer

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.

Demo Fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...