Question

I have a simple ko observable array of customer objects. In the view is a simple foreach data bind using the table/tr/td html elements. One of the properties of the customer object is a "notes" field that can contain up to 1000 characters.

When the view first loads, I am binding the text attribute of the "notes" property to a function that returns the first 100 characters of the note with "...." to indicate there's more text if applicable.

If the user clicks a checkbox to "view full notes" I want to refresh the notes column, only this time I don't substring it, I show the entire value. How do I get KO to re-evaluate the foreach, and specifically, can I just refresh the notes column?

The actual observable array values have not changed at all during this process, just the display is changing.

(using durandal 2.0 framework if it matters)

Was it helpful?

Solution

It can be done using a computed observable, like this (fiddle: http://jsfiddle.net/MA8Mu/2/):

html:

showFullNotes: <input type="checkbox" data-bind="checked:showFullNotes" /><br />
<table>
    <tbody data-bind="foreach:customers">
        <tr>
            <td>
                <span data-bind="text:actualNotes"></span>
            </td>
        </tr>
    </tbody>
</table>

js:

var Customer = function(notes, parent ){
    var self = this;
    self.notes = ko.observable(notes);

    self.actualNotes = ko.computed(function() {
        if (parent.showFullNotes()){
            return self.notes();
        } else {
            return self.notes().substring(0,5) + "...";
        }
    }, self);
} 


var VM = function(){
    var self = this;
    self.showFullNotes = ko.observable(false);
    self.customers = ko.observableArray(
        [new Customer("123456789", self),
        new Customer("abcderfgh", self)]
    );
}

var vm = new VM();
    ko.applyBindings(vm);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top