我接管了这个传统的.NET webforms应用程序,其中广泛使用了KO,我试图了解KO绑定。
设置: - 包含以下内容的母版页: - 用户控制Announcements.ascx - 对以其插入的页面命名的javascript文件的引用,让我们称之为helppageinit.js
helppageinit.js包含如下代码:
$(function () {
var basketViewModel = new AjaxBasket();
var quickBuy = new QuickBuyViewModel(basketViewModel);
$.when(basketViewModel.OnLoad, quickBuy.OnLoad).always(function () {
LeftBasketView(basketViewModel);
ko.applyBindings({ BasketViewModel: basketViewModel, QuickBuyViewModel: quickBuy });
});
});
我想将KO代码添加到名为AnnouncementsInit.js的新文件中,该文件在母版页上引用。 AnnouncementsInit.js的内容是:
$(window).load(function () {
var announcementsViewModel = new AnnouncementsViewModel();
$.when(announcementsViewModel.OnLoad).always(function () {
ko.applyBindings(announcementsViewModel, document.getElementById('announcementContainer'));
});
});
ko.bindingHandlers.stopBinding = {
init: function () {
return { controlsDescendantBindings: true };
}
};
AnnouncementsViewModel如下所示:
AnnouncementsViewModel = function (languange) {
var _onLoad = $.Deferred();
var _announcements = ko.observableArray();
var _singleAnnouncement = ko.observable();
var _imageWidth = ko.observable("40px");
var onClose = function () {
...code removed...
};
_onLoad.resolve();
return {
Announcements: _announcements,
SingleAnnouncement: _singleAnnouncement,
ImageWidth: _imageWidth,
OnClose: onClose,
OnLoad: _onLoad.promise()
};
};
Announements.ascx包含此标记:
<div data-bind="stopBinding: true">
<div id="announcementContainer">
<div class="popContainer" style="display: none">
<!-- ko if: SingleAnnouncement -->
...markup here
<!-- /ko -->
</div>
<div class="divModal" style="display: none" data-cookiename="<%= CookieName %>">
<!-- ko if: Announcements -->
...code here...
<!-- /ko -->
</div>
</div>
</div>
问题: 问题是stopBinding似乎无法正常工作。 '有时',我在控制台中收到此错误:
未捕获错误:无法解析绑定。 消息:ReferenceError:未定义公告; 绑定值:if:公告
我猜错误的发生是因为helppageInit.js中的applyBindings在announcementInit.js调用applyBindings之后应用绑定,即使stopBinding应该阻止它。
非常感谢任何帮助...