[英]Knockout component updating observable not being subscribed to by parent view model?
[英]Knockout Component View Not Updating When Its ViewModel Observable Changes
我有一個組件設置,可使用AMD獲取html模板和viewmodel代碼。 一切正常。 組件應按預期加載,並且在傳遞給它的參數下表現良好。 問題是我在viewModel中定義了一個可觀察對象,其值顯示在模板視圖中,但是當可觀察對象的值更改時,視圖上的文本不會更改。 誰能解釋這是怎么回事? 我要綁定的文本是modalTitle。 當模態加載時,其標題為“ TEMP”,但是如果我進入控制台並鍵入“ window.modalTitle()”,則會得到“ CREATE REPORT SCHEDULE”。 就像視圖正在獲取可觀察到的第一個值,然后在此之后將其忽略。 無論如何,我可以強迫它尋找更新嗎?
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 -->
它不會更改,因為this.itemName
尚未定義為可觀察的。 最好定義一個可計算的可觀測值,該值將在任何可觀測值更改時自動更新。
除了使用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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.