サーチ…


テキスト

textバインディングは、その要素のinnerTextを更新するためにどの要素でも使用できます。

<p>
  <span data-bind="text: greeting"></span>,
  <span data-bind="text: subject"></span>.
</p>
ko.applyBindings({
  greeting: ko.observable("Hello"),
  subject: ko.observable("world")
});

textバインディングは、仮想要素とともに使用することもできます。

<p>
  <!--ko text: greeting--><!--/ko-->, 
  <!--ko text: subject--><!--/ko-->.
</p>

CSS

このバインディングは、指定されたCSSクラスを要素に適用します。静的クラスは、指定された条件がtrueに緩やかに評価されたときに適用されます。動的クラスは、オブザーバブルまたは計算された値を使用します。

page.html

<p data-bind="css: { danger: isInDanger }">Checks external expression</p>
<p data-bind="css: { danger: dangerLevel() > 10 }">Expression can be inline</p>
<p data-bind="css: { danger: isInDanger, glow: shouldGlow }">Multiple classes</p>
<p data-bind="css: dynamicObservable">Dynamic CSS class from observable</p>
<p data-bind="css: dynamicComputed">Dynamic CSS class from computed</p>

page.js

ko.applyBindings({
  isInDanger: ko.observable(true),
  dangerLevel: ko.observable(5),
  isHot: ko.observable(true),
  shouldGlow: ko.observable(true),  
  dynamicObservable: ko.observable('highlighted'),
  dynamicComputed: ko.computed(function() {
        var customClass = "";
        if(dangerLevel() >= 15 ) {
            customClass += " danger";
        }
        if(dangerLevel() >= 10) {
            customClass += " glow";
        }
        if(dangerLevel() >= 5) {
            customClass += " highlighted";
        }
        return customClass;
    });
});

page.css

.danger { background: red; }
.glow { box-shadow: 5px 5px 5px gold; }
.highlighted { color: purple; }

参照: 公式文書

見える

DOM要素の表示/非表示に使用できます。 ifを使うのと似ていvisibleが、 visibleが要素を作り、 display:noneを設定する点が異なります。

<div data-bind="visible: shouldShowMessage">
    You will see this message only when "shouldShowMessage" holds a true value.
</div>
 
<script type="text/javascript">
    var viewModel = {
        shouldShowMessage: ko.observable(true);
    };
</script>

Attr

attrバインディングを使用して、要素に追加の属性を適用します。 href、src、または任意のデータ属性の設定に最も一般的に使用されます。

<img data-bind="attr: { src: url, title: title }"/>
var viewModel = {
    url: ko.observable("images/example.png"),
    title: "example title"
};

HTML

このバインディングは、jQueryが参照された場合はjQuery.html()を使用して要素のinnerHTMLを更新し、それ以外の場合はKO独自の解析ロジックを更新します。 API、RSSフィードなどからHTMLを取得する場合に便利です。このタグをユーザー入力HTMLとともに使用することに注意してください。

page.html

<p>
  <span data-bind="html: demoLink"></span>
</p>

page.js

ko.applyBindings({
  demoLink: ko.observable("<a href='#'>Make a link</a>")
});


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow