1
請參閱附加的代碼。observable不更新自定義綁定
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>
是的,你應該永遠不會需要使用'__latestValue'直接 - 除非,也許,你正在寫一個淘汰賽插件...即使這樣,我會盡可能避免它。 –
是的,你是對的。 value()(1)註冊依賴關係,以便再次調用update(),(2)返回__latestValue。 –