请参阅随附的代码。
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>
答案 0 :(得分: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);
}
};