Reputation: 5531
I have a Table where in Data comes dynamically depending on some condition. I wish to some data For example on click of button.
if(true){
Show: ABC Data
}
else{
Show XYZ Data
}
Here is the Fiddle I used to expand my functionality but unfortunately I am stuck on this requirement.
Upvotes: 0
Views: 37
Reputation: 23372
In your viewmodel constructor, you've defined some logic on how to load data:
self.items = ko.observableArray(data.map(function(i) {
return new rowModel(i.id, i.name, i.status);
}));
Because items
is an observable array, you're free to update its contents whenever you like!
Let's move the mapping logic to a separate function:
self.loadData = function(rawData) {
var viewmodels = rawData.map(function(d) {
return new RowModel(d.id, d.name, d.status);
});
self.items(viewmodels);
};
In your constructor, you can now load the initial data like so:
self.items = ko.observableArray();
self.loadData(data);
In the click
callback of your button, you'll reuse our new loadData
method:
self.changeTableData = function() {
if (someCondition()) {
self.loadData([ /* ... */ ]);
} else {
self.loadData([ /* ... */ ]);
}
}
Optional:
For purely aesthetic reasons, I usually define a static constructor helper for easy mapping:
RowModel.fromRawDataPoint = function(dataPoint) {
return new RowModel(dataPoint.id, dataPoint.name, dataPoint.status);
};
I'd move the functions defined in the constructor to the VM's prototype:
MyVM.prototype.loadData = function(rawData) {
this.items(rawData.map(RowModel.fromRawDataPoint));
};
Here's an updated fiddle: https://jsfiddle.net/975ncawv/
Upvotes: 1