I think the first way (multiple variables) is best, as you can otherwise end up with this (from an application that uses KnockoutJS), which is difficult to read in my opinion:
var categories = ko.observableArray(),
keywordFilter = ko.observableArray(),
omniFilter = ko.observable('').extend({ throttle: 300 }),
filteredCategories = ko.computed(function () {
var underlyingArray = categories();
return ko.utils.arrayFilter(underlyingArray, function (n) {
return n.FilteredSportCount() > 0;
});
}),
favoriteSports = ko.computed(function () {
var sports = ko.observableArray();
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
sports.push(a);
}
});
});
return sports;
}),
toggleFavorite = function (sport, userId) {
var isFavorite = sport.IsFavorite();
var url = setfavouritesurl;
var data = {
userId: userId,
sportId: sport.Id(),
isFavourite: !isFavorite
};
var callback = function () {
sport.IsFavorite(!isFavorite);
};
jQuery.support.cors = true;
jQuery.ajax({
url: url,
type: "GET",
data: data,
success: callback
});
},
hasfavoriteSports = ko.computed(function () {
var result = false;
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
result = true;
}
});
});
return result;
});