我在使用knockout.js从子对象获取父对象的某个字段时遇到困难。
function Child(info){
var self = this;
self.x = info.x;
self.y = info.y;
self.parentThing = parent.fieldToGet(); // This is when I had problem
}
function Main() {
var self = this;
self.fieldToGet = ko.observable();
self.things = ko.observableArray();
self.postFunction = function(){
$.post('XXX.php', $("form#filterForm").serialize(), function(data){
var mappedThing = $.map(data.data, function(info){return new Child(info); });
self.things(mappedThing);
}
}, 'json');
};
}
var main = new Main();
ko.applyBindings(main, $("div#main")[0]);
层次结构是Main有几个Child。在Child对象中,我想获得其父项的属性:fieldToGet。
答案 0 :(得分:4)
我认为一个好的解决方案是将父类作为参数传递给子项。
function Child(info, parent){
var self = this;
self.parent = parent;
self.x = info.x;
self.y = info.y;
self.parentThing = parent.fieldToGet(); // This is when I had problem
}
function Main() {
var self = this;
self.fieldToGet = ko.observable();
self.things = ko.observableArray();
self.postFunction = function()
{
$.post('XXX.php', $("form#filterForm").serialize(), function(data) {
var mappedThing = $.map(data.data, function(info) {
return new Child(info, self);
});
self.things(mappedThing);
}, 'json');
};
}
var main = new Main();
ko.applyBindings(main, $("div#main")[0]);
正如您在我的示例中所看到的,父实例(self
)将作为参数传递给构造函数中的子类(function Child(info, parent)
)