请参考随附的代码。
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>