Knockoutjs:将foreach中的动态iframe绑定到父级 [英] Knockoutjs: bind dynamic iframes in foreach to parent
问题描述
我正在尝试绑定iframe和父窗口,以便我可以在iframe或父窗口中更改/更新observable,并且两个视图都将使用新值进行更新。
I am trying to bind iframe and parent window so that I can change/update an observable in either the iframe or parent window and both views will update with new value.
以下是工作示例: http://jsfiddle.net/NnT78/26/
我已经调整了一些我找到的示例代码,并使其运行良好如下;
HTML:
<iframe src="http://fiddle.jshell.net/zVPF8/11/show/" data-bind="bindIframe: $data"></iframe>
但是当我在foreach绑定中放入相同的html时会出现错误;
HTML:
<ul data-bind="foreach: iframes">
<li>
<iframe data-bind="attr: {src: src}, bindIframe: $data"></iframe>
</li>
</ul>
错误:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: text: someProperty
Message: someProperty is not defined
这是我的Knockoutjs ViewModel代码;
ko.bindingHandlers.bindIframe = {
init: function(element, valueAccessor) {
function bindIframe() {
try {
var iframeInit = element.contentWindow.initChildFrame,
iframedoc = element.contentDocument.body;
} catch(e) {
// ignored
}
if (iframeInit)
iframeInit(ko, valueAccessor());
else if (iframedoc){
ko.applyBindings(valueAccessor(), iframedoc);
}
};
bindIframe();
ko.utils.registerEventHandler(element, 'load', bindIframe);
}
};
function ViewModel() {
var self = this;
self.someProperty = ko.observable(123);
self.clickMe = function(data, event) {
self.someProperty(self.someProperty() + 1);
}
self.anotherObservableArray = ko.observableArray([
{ name: "Bungle", type: "Bear" },
{ name: "George", type: "Hippo" },
{ name: "Zippy", type: "Unknown" }
]);
self.iframes = ko.observableArray([
{ src: "http://fiddle.jshell.net/zVPF8/6/show/", type: "Bear" },
{ src: "http://fiddle.jshell.net/zVPF8/6/show/", type: "Hippo" },
{ src: "http://fiddle.jshell.net/zVPF8/6/show/", type: "Unknown" }
]);
};
// Bind outer doc
ko.applyBindings(new ViewModel());
参见 http://jsfiddle.net/NnT78/26/ 单个iframe工作样本和foreach绑定中的动态iframe无法正常工作。
See http://jsfiddle.net/NnT78/26/ for sample of single iframe working and dynamic iframes in foreach bind not working.
在此先感谢!
推荐答案
在 foreach
绑定时, $ data
是不同的;它是数组中的当前项。您可以通过更改 iframe
来绑定到 $ root
来修复您的示例。
When in a foreach
binding, $data
is different; it's the current item in the array. You can fix your example by changing the iframe
to bind to $root
instead.
<iframe data-bind="attr: {src: src}, bindIframe: $root"></iframe>
http://jsfiddle.net/mbest/NnT78/29/
这篇关于Knockoutjs:将foreach中的动态iframe绑定到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!