Reference local fields in computed

15 views
Skip to first unread message

Steven Hayhurst

unread,
Jan 11, 2017, 12:13:22 PM1/11/17
to KnockoutJS
Hi, I'm new to KO and having trouble getting a computed value to work.  I've got a complicated viewmodel because I have many objects inside.  This is an example of how I set the VM up.  Feel free to correct anything I'm doing wrong in here (although it does work apart from the computed value):

var viewModel = function(object1, object2...) {
    var self = this;
    var activeProductCodes = ['AB-1', 'AB-2', 'AB-3'];

    self.myFirstObject = ko.observable({
        field1: ko.observable(object1.field1),
        field2: ko.observable(object1.field2),
        field3: ko.observable(object1.field3)
    });
   
   
    self.mySecondObject = ko.observable({
        productCode: ko.observable(object2.productCode),
       
        isActiveProduct: ko.computed(function() {
            return self.activeProductCodes.indexOf(ProductCode) !== -1 ? true : false;
        }, self)
    });
}


isActiveProduct doesn't work.  It doesn't know what productCode is.  I've tried doing this., self., self.mySecondObject()., none of them seem to work.
Is it possible to access the value?

Thanks
Steven

noirabys

unread,
Jan 12, 2017, 3:39:58 AM1/12/17
to KnockoutJS
hi,
i think in your computed you throw in self which is the viewModel and not the object you've created 
try to replace the json object literal with;

function MyObject(activeProductCodes,productCode){
  var self = this;
  self.productCode= ko.observable(productCode);
  self.activeProductCodes = activeProductCodes;
  self.isActiveProduct=ko.computed(function() {
            return self.activeProductCodes.indexOf(self.productCode()) !== -1 ? true : false;
        });
}

...
    self.mySecondObject = ko.observable(new MyObject(self.activeProductCodes,object2.productCode));

best regards,
 noirabys

Steven Hayhurst

unread,
Jan 13, 2017, 4:13:15 AM1/13/17
to KnockoutJS
Thanks for your response, I think you're right.  I have since had some feedback on stackoverflow to the same question and fixed the problem.  I've split object creation out so self always refers to the current object so I think your solution would've worked too.  Thanks
Reply all
Reply to author
Forward
0 new messages