Knockout.js-在视图模型中使用循环引用进行调试 [英] knockoutjs - debug with circular reference in view model
问题描述
根据设计,视图模型具有循环引用,利用<pre data-bind="text: ko.toJSON($data)"></pre>
进行调试以抛出:
The view model has a circular reference, by design, making the use of <pre data-bind="text: ko.toJSON($data)"></pre>
for debugging to throw:
Unable to parse bindings.
Message: TypeError: Converting circular structure to JSON;
Bindings value: text: ko.toJSON($data)
有没有办法解决这个问题?
Is there a way to work around this?
推荐答案
最终导致您出错的是ko.toJSON
内部对JSON.stringify
的调用.
It is ultimately the call to JSON.stringify
inside of ko.toJSON
that causes your error.
一种控制JSON输出的方法是通过在对象上提供toJSON
函数,如下所述:
One way that you can control the output of your JSON is by supplying a toJSON
function on your object as described here: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html. That way you can remove the circular reference in the appropriate place.
您还可以使用其他一些技术.
There are a few other techniques that you could use for this as well.
-
您可以将第二个参数传递给
ko.toJSON
.这是JSON.stringify
的replacer
选项,如下所述:
You can pass a second argument to
ko.toJSON
. This is thereplacer
option toJSON.stringify
as described here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON /stringify .
例如,您可以传递一组属性以包括:
For example, you can pass an array of properties to include like:
ko.toJSON(myobject, ["one", "two", "three"])
您可以将您不想将其变成JSON的属性附加为"sub" -observable,例如:
You can attach a property that you don't want to get turned into JSON as a "sub"-observable like:
this.data = ko.observable();
this.data.parent = parent;
在这种情况下,data
会变成JSON
,但是parent
会消失,因为它是可观察对象的一个属性,已经解开了它的值.
In this case, data
will get turned into JSON
, but parent
will just disappear, as it is a property on an observable that already gets unwrapped into its value.
这篇关于Knockout.js-在视图模型中使用循环引用进行调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!