是否有办法触发此 JS Fiddle 中我的元素的标题属性的更新:
请注意,元素的 data-bind 属性中的工具提示是 knockout-bootstrap.js 库的一部分
<label data-bind="text: copyOtherPartyHelpText()"></label>
<br />
<br />
<i class="icon-question-sign" data-bind="tooltip: { title: copyOtherPartyHelpText(), placement: 'top', trigger: 'hover' }"></i>
<br />
<br />
<a style="cursor: pointer;" data-bind="click:changeHelpText">Click HERE To Change Label Text</a>
function MyViewModel() {
this._copyOtherPartyHelpText = ko.observable();
this.readOnlyView = ko.observable(true);
this.copyOtherPartyHelpText = ko.computed({
read: function () {
var value = this._copyOtherPartyHelpText();
if (value) {
return value;
}
if (this.readOnlyView()) {
value = 'Currently Disabled';
} else {
value = 'Match/agree to this term.';
}
//this makes things even worse, it is an initialization workaround
//_copyOtherPartyHelpText(value);
return value;
},
write: function (value) {
this._copyOtherPartyHelpText(value);
},
owner: this
});
this.changeHelpText = function(){
this.copyOtherPartyHelpText('help text updated but not tooltip');
}
}
ko.applyBindings(new MyViewModel());
最佳答案
控制台/浏览器错误日志会告诉您:
Uncaught ReferenceError: copyOtherPartyHelpText is not defined
您必须使用 this.
引用您的函数调用,否则内部函数将改为寻找 window.copyOtherPartyHelpText。
我建议在 View 模型中使用名为 self
的局部变量(正如它们在 KnockoutJS 文档和教程中经常做的那样),这样您就可以始终从内部安全、轻松地引用其属性,如修改后的 JSFiddle 所示:http://jsfiddle.net/YPXYJ/3/
function MyViewModel() {
var self = this;
// More code here...
this.changeHelpText = function(){
alert('changeHelpText called');
self.copyOtherPartyHelpText('help text and UI updated');
}
}
编辑2:
在标题的工具提示绑定(bind)内,您不会调用值访问器,而是引用可观察函数,如下所示:
旧:
<i class="icon-question-sign" data-bind="tooltip: { title: copyOtherPartyHelpText(), placement: 'top', trigger: 'hover' }"></i>
新:
<i class="icon-question-sign" data-bind="tooltip: { title: copyOtherPartyHelpText, placement: 'top', trigger: 'hover' }"></i>
关于javascript - 计算的可观察更改不会更新 UI 中的标题属性(使用 Knockout-bootstrap.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022400/