我遇到的问题是 IE Knockout 2.3.0 , IE 内存泄漏。我有一个显示在屏幕上的结果列表,结果集具有分页功能。有一个AJAX回调给控制器以获取下一组分页结果。当最初将第一页绑定到屏幕时,IE的内存负载大约为150Mb,但每页增加大约50Mb到100Mb,Chrome或FireFox中不会出现此问题。
这个问题似乎很常见,我看了很多例子,例如: KnockoutJS Memory Leak 我试图复制这个模型无济于事,这就是我的KO脚本文件的样子:
var householdViewModel = ko.observable();
var HouseholdViewModel = function (data) {
ko.mapping.fromJS(data, mapping, this);
};
var AccountViewModel = function (data) {
ko.mapping.fromJS(data, mapping, this);
};
var mapping = {
'Households': {
create: function(options) {
return new HouseholdViewModel(options.data);
}
},
'Accounts': {
create: function (options) {
return new AccountViewModel(options.data);
}
}
};
我正在使用MVC框架来执行我的AJAX调用,如下所示:
@Ajax.ActionLink(">", "PageInfo", new {pageOption = "Next"}, new AjaxOptions {UpdateTargetId = "SearchResults", HttpMethod = "GET", OnBegin = "OnBeginAjaxListManipulation", OnComplete = "OnCompleteAjaxListManipulation"}, new {@class = "textNavigationElement"})
使用回调JS方法,如下所示:
function OnCompleteAjaxListManipulation() {
//ko.cleanNode(document.getElementById("SearchResults"));
var HHVM = { Households: ko.mapping.fromJS(@Html.Raw(Json.Encode(Model.Households))) };
householdViewModel(new HouseholdViewModel(HHVM));
//ko.applyBindings(householdViewModel, document.getElementById("SearchResults"));
}
我想我需要说明我有一个名为Info.cshtml的页面和一个名为results.cshtml的部分页面,它将显示搜索结果。在信息页面中,我进行了以下调用;
var HHVM = { Households: ko.mapping.fromJS(@Html.Raw(Json.Encode(Model.Households))) };
householdViewModel(new HouseholdViewModel(HHVM));
ko.applyBindings(householdViewModel, document.getElementById("SearchResults"));
搜索结果将在第一页显示正常,但第二页显示无效。如果我在JS回调中添加第二个applyBindings它可以工作但我得到内存泄漏问题。我无法想出这一点,任何帮助将不胜感激。
约什
答案 0 :(得分:0)
我通过手动控制可观察数组来修复它,这可能就是你应该这样做的方式。首先,我将我的模型改为:
var Households = ko.observableArray(HouseholdViewModel);
var HouseholdViewModel = function (data) {
ko.mapping.fromJS(data, mapping, this);
};
var AccountViewModel = function (data) {
ko.mapping.fromJS(data, mapping, this);
};
var mapping = {
'Households': {
create: function(options) {
return new HouseholdViewModel(options.data);
}
},
'Accounts': {
create: function (options) {
return new AccountViewModel(options.data);
}
}
};
然后改变了触发Ajax调用的方式,我删除了UpdateTargetId并决定自己控制代码如下:
@Ajax.ActionLink(">>", "PageInfo", new {pageOption = "Last"}, new AjaxOptions {HttpMethod = "GET", OnBegin = "OnBeginAjaxListManipulation", OnComplete = "OnCompleteAjaxListManipulation", OnSuccess = "BindModel"}, new {@class = "textNavigationElement"})
function BindModel(e) {
var isBound = !!ko.dataFor(document.getElementById("SearchResults"));
if (isBound)
Households.removeAll();
$.each(e.Households, function (index, value) {
var hh = new HouseholdViewModel(value);
Households.push(hh);
});
if (!isBound)
ko.applyBindings(Households, document.getElementById("SearchResults"));
}
就是这样!结果是,每次绑定模型时,它将清除可观察数组并读取项目,因为将可观察数组绑定到页面,我们不需要执行任何ko.CleanNode和重新绑定: - )
我希望这可以帮助别人。