构建子对象时,将父对象作为参数(指针)过滤到子模型的最简单方法。但更多的标准JavaScript的方式,然后淘汰赛
var Parent = function (item) {
var self = this;
this.value = ko.observable(item.value);
this.child = new Child(item.child, self);
}
var Child = function (item, parent) {
var self = this;
this.parent = parent;
this.value = ko.observable(item.value);
}
和HTML标记看起来像
This is <b><span data-bind="text: value"></span></b>
<div data-bind="with: child">
This is <b><span data-bind="text: value"></span></b>
<br/>
This is <b><span data-bind="text: parent.value"></span></b> of <b><span data-bind="text: value"></span></b>
</div>
JSFIDDLE
为了防止可用于代码映射插件的大金额,这将是更多淘汰赛方式
var Parent = function (item) {
var self = this;
var map = {
'child': {
update: function(options) {
return new Child(options.data, self);
}
}
}
ko.mapping.fromJS(item, map, self);
}
var Child = function (item, parent) {
var self = this;
this.parent = parent;
ko.mapping.fromJS(item, null, self);
}
JSFIDDLE
而且最淘汰赛的方式 - 它来创建自定义绑定将控制descendant bindings。通过这种方式,您可以扩展具有额外属性的子上下文。
ko.bindingHandlers.withParent = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Make a modified binding context, with a extra properties, and apply it to descendant elements
ko.mapping.fromJS({
parent: bindingContext.$rawData
}, null,valueAccessor());
var childBindingContext = bindingContext.createChildContext(valueAccessor, null, null);
ko.applyBindingsToDescendants(childBindingContext, element);
// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true };
}
};
型号
var Parent = function (item) {
var self = this;
var map = {
'child': {
update: function(options) {
return new Child(options.data);
}
}
}
ko.mapping.fromJS(item, map, self);
}
var Child = function (item, parent) {
var self = this;
ko.mapping.fromJS(item, null, self);
}
和HTML
This is <b><span data-bind="text: value"></span></b>
<div data-bind="withParent: child">
This is <b><span data-bind="text: value"></span></b>
<br/>
This is <b><span data-bind="text: parent.value"></span></b> of <b><span data-bind="text: value"></span></b>
<br/>
<input type="button" value="Test from code" data-bind="click: test"/>
</div>
JSFIDDLE
但本人来说我不喜欢这种方式,因为用起来 '有', '的foreach'或'tempalate'绑定它可能会导致错误像
消息:您不能将绑定多次应用于同一元素。