2

要素自体がビュー モデルに含まれるように要素をバインドするにはどうすればよいですか? 使いたくないdocument.getElementByID

HTML

<div id="someDiv" data-bind="self: someDiv" />

ビューモデル

viewModel.someDiv = ko.observable();

(viewModel.someDiv() === document.getElementByID('someDiv')) === true;

編集:

いくつかのコンテキスト...グラフライブラリを呼び出すラッパーレイヤーの別のビューモデルをサブスクライブしました。グラフ ライブラリがレンダリングする要素をバインドしたいと思います。

4

3 に答える 3

3

オブザーバブルを設定するカスタム バインディングを作成できます。

ko.bindingHandlers.bindElement = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = valueAccessor();
        value(element);
    }

    };

<div id="someDiv" data-bind="bindElement: myElement">

フィドルを参照してください:リンク

于 2012-09-07T20:07:07.947 に答える
2

Accessing the view directly from the view model goes against the separation principle of MVVM. Perhaps better is to use a custom binding handler as a behavior - the binding handler's init and update functions will give you access to the DOM element itself. This way, the behavior can be added from the view in a declarative manner.

More information about exactly what you are trying to achieve would help in giving a useful answer.

于 2012-09-07T20:29:30.007 に答える
0

次のように、document.getElementById('') によって返される要素にオブザーバブルを設定します。

viewModel.someDiv = ko.observable(document.getElementById('someDiv'));

あなたの例と同様のことを示すために、いくつかの if ステートメントを使用してフィドルを作成しました。

http://jsfiddle.net/Rynan/DnXrd/

于 2012-09-07T17:54:03.287 に答える