1

请参考随附的代码。

DummyText是可观察的,并且在ko.bindingHandlers.dummytext. 但是,this.DummyText("dummy_text_" + this.firstName());只调用update: function (element, valueAccessor,....一次,因此<span data-bind="dummytext: DummyText"></span>只更新一次。

文本被创建为文本绑定的参考,并且<span data-bind="text: Text"></span>始终更新。

如何让this.DummyText("dummy_text_" + this.firstName());总是打电话update: function (element, valueAccessor,....

<html>
<head>
</head>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.debug.js"></script>
<body>
    <p>First name: <input data-bind="value: firstName" /></p>
    <p>Last name: <input data-bind="value: lastName" /></p>
    <h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
    <div><span data-bind="text: Text"></span></div>
    <div><span data-bind="dummytext: DummyText"></span></div>

    <script>
        ko.bindingHandlers.dummytext = {
            //init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            //},
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var value = valueAccessor(), allBindings = allBindingsAccessor();
                var s = value._latestValue;
                $(element).html(s);
            }
        };

        var ViewModel = function (first, last) {
            this.firstName = ko.observable(first);
            this.lastName = last;
            this.DummyText = ko.observable("dummy_text_");
            this.Text = ko.observable("text_");

            this.fullName = ko.computed(function () {
                this.Text("text_" + this.firstName());
                this.DummyText("dummy_text_" + this.firstName());

                return this.firstName() + " " + this.lastName;
            }, this);
        };

        ko.applyBindings(new ViewModel("Planet", "Earth"));
        </script>

</body>
</html>
4

1 回答 1

2

您应该使用 value() 而不是 value._latestValue 来触发依赖项,以便 Knockout 可以知道在值更新时当前绑定需要刷新:

看看这个:http: //jsfiddle.net/b4bDQ/

ko.bindingHandlers.dummytext = {
        //init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //},
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var value = valueAccessor(), allBindings = allBindingsAccessor();
            var s = value(); // Here should use () to trigger the subcribing dependency // value._latestValue;
            $(element).html(s);
        }
    };
于 2013-08-21T19:01:21.820 回答