0

I am mapping two related models by storing the primary key of related model in the first and then computing the actual model at runtime. This cause my model to access the view-model list. Is there any better way of relating these models

function Address(data){
  this.id = data.id;
}

function Person(data){
  var self = this;

  self.addressIdList = ko.observableArray();

  this.addresses = ko.computed(function(){
        return _.filter(_.map(self.addressIdList(), function(id){
            return _.find(vm.addressList(), function(a){
                return a.id == id;
            });
        }),function(item){ return typeof item != 'undefined';});    
  });
}

function ViewModel(){
  this.personList = ko.observableArray();
  this.addressList = ko.observableArray();
}

var vm = new ViewModel();
  • I want to remove access to view-model (vm.addressList()) from Person.addresses(). How can I do this?
  • Will JayData or some other library help me ?
goto
  • 433
  • 3
  • 13

2 Answers2

1

Answering my own question...

Instead of storing id's of related models, I store references of related models itself. Thus you can go from one model to another without accessing the view-model

So

self.addressIdList = ko.observableArray();
self.addresses = ko.observableArray();

Complete example here

goto
  • 433
  • 3
  • 13
0

I'm from JayData. Is it a master-detail scenario and your data comes from a database ? If yes, then you can achieve it with JayData with a few lines of code, see this example: http://jaydata.org/examples/Knockout/DynamicQueryFilterNorthwind

Gabor Dolla
  • 2,680
  • 4
  • 14
  • 13