2011-11-08 13 views
2

私はそれが意味をなさないとは確信しています。それを語る方法がわからない他の観察可能なオブジェクトからオブジェクトにアクセスする方法

基本的にはこれがあります。

function Line(id, name, equipType, model, height, length, loadsWeek, weight, width, pallets) { 

    this.id = ko.observable(id); 
    this.name = ko.observable(name);   
    this.height = ko.observable(height); 
    this.length = ko.observable(length); 
    this.weight = ko.observable(weight); 
    this.width = ko.observable(width); 
    this.model = ko.observable(model); 
    this.equipType = ko.observable(equipType); 
    this.loadsWeek = ko.observable(loadsWeek); 

this.perimeter = ko.dependentObservable(function() { 
     return parseInt(this.height()) + parseInt(this.length()) 
    }, this); 

    var mapped = ko.utils.arrayMap(pallets, function(pallet) {    
     return new Pallet(pallet.id, pallet.name, pallet.height, pallet.width, this)  
    }); 

    this.pallets = ko.observableArray(mapped); 
} 

function Pallet(id, name, height, width, line) { 

    this.id = ko.observable(id); 
    this.name = ko.observable(name); 
    this.height = ko.observable(height); 
    this.width = ko.observable(width); 
    this.line = ko.dependentObservable(line); 
      //calculate something here that uses a variable from Line 

} 

パレットでは、ラインオブジェクトにアクセスして値を取得する必要があります。 Lineオブジェクトの値を必要とする計算を行います。私は明らかに "this"(行)をパレットオブジェクトに渡すことができないので、このコードは今は動作しません。

は、ここであなたが考えるのと同じthisではありません、おそらくあなたはarrayMapに渡している匿名関数内でそのthisあるコード

var viewModel = {  
    lines: ko.observableArray([]),  
    activeTab: ko.observable() 
}; 

$.getJSON("/json/all/lines", { customer_id : customer_id } , function(data) {  

     //ko.mapping.fromJS(data, null, viewModel.lines);   

     var mappedData = ko.utils.arrayMap(data, function(line) { 

      return new Line(line.id, line.name, line.equipType, line.model, line.height, line.length, line.loadsWeek, line.weight, line.width, line.pallets)   
     }); 

}); 

答えて

5

問題の残りの部分です。

var that = this; 
var mapped = ko.utils.arrayMap(pallets, function(pallet) { 
    return new Pallet(pallet.id, pallet.name, pallet.height, pallet.width, that) 
}); 

------その後

function Pallet(id, name, height, width, line) {   
    this.id = ko.observable(id);  
    this.name = ko.observable(name);  
    this.height = ko.observable(height);   
    this.width = ko.observable(width);  
    this.line = ko.dependentObservable(line);    
    //calculate something here that uses a variable from Line  

    this.something = ko.observable(function() { 
     return this.line().somethingFromParent(); 
    }); 
    } 
+0

ありがとう:

のようなものを試してみてください。これは間違っている。私はその段階にいないと思った。ハハ。 –

関連する問題