我有一个组件设置,使用AMD来获取html模板和viewmodel代码。一切正常。组件在应该加载时加载,并且传递给它的参数表现良好。问题是我在viewModel中定义了一个observable,其值显示在模板视图中,但是当observable的值发生更改时,视图上的文本不会更改。谁能解释一下这里发生了什么?我试图绑定的文本是modalTitle。当模态加载它的标题是'TEMP'但如果我去控制台并输入'window.modalTitle()'我得到'CREATE REPORT SCHEDULE'。这就像视图获得了observable的第一个值,然后忽略它。无论如何我可以强迫它寻找更新吗?
ViewModel :( schedules.component.js)
define(['knockout'], function (ko) {
console.log('schedules hit');
loadCss('schedules');
function SchedulesViewModel(params) {
this.scheduledItems = params.scheduledItems;
this.itemName = params.itemName;
this.modalTitle = ko.observable("TEMP");
window.modalTitle = this.modalTitle;
}
SchedulesViewModel.prototype.initiateAddScheduledItem = function () {
this.modalTitle("CREATE " + this.itemName + " SCHEDULE");
$('#schedulesModal').modal('show');
};
SchedulesViewModel.prototype.removeSelectedScheduledItem = function () {
this.chosenValue('dislike');
};
window.ReportsApp.SchedulesViewModel = SchedulesViewModel;
return SchedulesViewModel;
});
查看模板
<div id="schedulesModal" class="modal fade lcmsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>-->
<img src="/Content/images/modalASLogo.png" style="float: right;" />
<h4 class="modal-title" data-bind="text: modalTitle()">Test Title</h4>
</div>
<div class="modal-body">
<p>One fine body ...</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">CANCEL</button>
<button type="button" class="btn btn-primary">SAVE</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /Bootstrap Modal -->
答案 0 :(得分:2)
它没有被更改,因为this.itemName
尚未被定义为可观察对象。最好定义一个计算的observable,它会在任何observable发生变化时自动更新。
而不是使用prototype
添加方法,您可以使用淘汰功能,为您提供它。
示例:https://jsfiddle.net/kyr6w2x3/34/
function SchedulesViewModel(params) {
var self = this ;
self.scheduledItems = ko.observable(params.scheduledItems);
self.itemName = ko.observable(params.itemName);
self.modalTitle = ko.observable("TEMP");
self.chosenValue= ko.observable();
self.modalTitle = ko.computed(function() {
return "CREATE " + self.itemName() + " SCHEDULE" ;
}, self);
// you can change below to show your modal whenever you want
$('#schedulesModal').modal('show');
self.removeSelectedScheduledItem = function (){
self.chosenValue('dislike');
}
}
ko.applyBindings(new SchedulesViewModel({scheduledItems:"scheduledItems" ,itemName : "itemName" }));
更新:是的,您可以拥有多个视图模型,或者更好地说嵌套视图模型。查看新示例,了解如何在模型之间进行通信。https://jsfiddle.net/kyr6w2x3/35/