Reputation: 588
I can´t seem to get this right: http://jsfiddle.net/dPyQy/4/
I want to collect the tags I am entering in the input field for saving. I need to reference the Textbatches as a SelectedText as in RL I need to be able to choose among Textbatches.
var Textbatch = function (data,tags) {
var self = this;
self.TextbatchId = data.TextbatchId;
self.Title = ko.observable(data.Title);
self.Text = ko.observable(data.Text);
self.TextTags = ko.observableArray(tags);
function createTypeComputed(tagType) {
return ko.computed(function () {
return ko.utils.arrayFilter(self.TextTags(), function (item) {
return item.Type() == tagType;
});
});
}
self.managerTags = createTypeComputed(0);
self.removeTag = function (tagToRemove) {
self.TextTags.remove(function (item) {
return item.Id == tagToRemove.Id;
});
}
}
Struggling with the contexts and the objects and everything. I want the chosen tags listed beneath the input-field, and then the debug to show the updated object.
Any help highly appreciated. Thanx.
Upvotes: 1
Views: 81
Reputation: 15003
managerTags
evaluates to an array, but you're using it in a text
binding which is expecting it to evaluate to a string.
How do you want to display it? As an HTML list (use a foreach
binding to loop over the tags), or as a comma (or something)-separated string (use join
on it)?
To get a comma-separated string, change createTypeComputed
to
function createTypeComputed(tagType) {
return ko.computed(function () {
return ko.utils.arrayMap(
ko.utils.arrayFilter(self.TextTags(), function (item) {
return item.Type() == tagType;
}),
function (item) {
return item.Name();
}).join(',');
});
}
Note that if you can count on using an ES5 browser (anything but IE<9) you can simplify the function for the computed to
return self.TextTags().filter(function (item) {
return item.Type() == tagType;
})
.map(function (item) {
return item.Name();
})
.join(',');
Upvotes: 1