1

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.

1 Answer 1

1

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(',');
Sign up to request clarification or add additional context in comments.

6 Comments

I´d like a comma-separated string.
So modify your computed to return a string by using the filtered array's join method.
Sorry, I cannot see that (alone at least) helping. Can you be more specific?
Thanx. I have included that in an updated fiddle jsfiddle.net/dPyQy/5 , but still I have the same problems with printing out the managerTags (see "Local managers"-string and second debug-string in fiddle.
My mistake: forgot to extract the Name field from the objects; see updated answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.