knockout.js映射导致IE9无限递归 [英] knockout.js mapping causing infinite recursion on IE9
问题描述
我通过knockout.js映射在IE上进行无限递归。有人可以更熟悉KO来发现我做错了吗?
I'm having endless recursion on IE by my knockout.js mapping. Can someone more familiar with KO to spot what am I doing wrong?
我有以下knockout.js映射:
I have following knockout.js mapping:
var mapping = {
create: function(options) {
return new MyViewModel(options.data);
},
'ChildItems': {
create: function(options) {
return new ChildVM(options.data);
}
}
}
当我渲染页面时。 5个IE中的1个时间最终跟随无限递归堆栈(导致SCRIPT28:堆栈空间不足)。 IE的callstack:
When I render the page approx. 1 time out of 5 IE ends up with following infinite recursion stack(causing "SCRIPT28: Out of stack space"). IE's callstack:
fromJS
MyViewModel
create
Anonymous Function
withProxyDependentObservable
createCallback
updateViewModel
fromJS
MyViewModel
create
Anonymous Function
withProxyDependentObservable
createCallback
updateViewModel
...
我的视图模型构造函数:
My view model constructor:
function MyViewModel(data) {
var self = this;
this.$type = 'MyViewModel';
[some observables]
...
ko.mapping.fromJS(data, mapping, this);
}
通过调用json端点来初始化视图模型: / p>
Initializing of view model is done by calling json endpoint:
$.ajax({
url: 'http://my.end/point',
type: 'POST',
data: JSON.stringify(payload),
contentType: 'application/json; charset=utf-8',
success: function(data) {
window.vm = ko.mapping.fromJS(data, mapping);
ko.applyBindings(window.vm)
}
});
推荐答案
您应该将映射对象划分为2个对象。首先用于映射视图模型,第二个用于子视图。
You should divide your mapping object to 2 objects. Use first for mapping view model and second for children.
var mapping = {
create: function(options) {
return new MyViewModel(options.data);
}
}
var childrenMapping = {
'ChildItems': {
create: function(options) {
return new ChildVM(options.data);
}
}
}
您的ajax请求保持不变。更新MyViewModel函数以使用childrenMapping:
Your ajax request remain the same. Update MyViewModel function to use childrenMapping :
function MyViewModel(data) {
var self = this;
this.$type = 'MyViewModel';
[some observables]
...
ko.mapping.fromJS(data, childrenMapping, this);
}
问题的根本原因是递归调用映射。当你调用 ko.mapping.fromJS(数据,映射);
敲门调用创建规则时创建MyViewModel对象。在MyViewModel的构造函数中,您调用 ko.mapping.fromJS
,因为使用了相同的映射选项,knockout调用创建MyViewModel对象的相同创建规则,其中 ko使用相同的选项调用.mapping.fromJS
。
The root cause of the issue is recursive calling of mapping. When you call ko.mapping.fromJS(data, mapping);
knockout calls create rule where creates MyViewModel object. In MyViewModel's constructor you call ko.mapping.fromJS
due to the using of the same mapping options knockout calls the same create rule that creates MyViewModel object where ko.mapping.fromJS
is called with the same options.
这篇关于knockout.js映射导致IE9无限递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!