3

I'm fairly new to Knockout.js so I may simply be missing something. I'm trying to create a set of divs that work as buttons where their 'selected' state reflects a subvalue of an item in an array.

See this fiddle: http://jsfiddle.net/bleiddyn/RepnY/

Excerpt:

    $('.tag-cell').click(function() {
        var ele = event.srcElement.textContent;
        var match = ko.utils.arrayFirst(self.Tags(), function(item) {
            if (ele === item.title) {
                item.chosen = !item.chosen;
                return true;
            }
            return false;
        });

        match.chosen = true;
        self.Tags.valueHasMutated();
    });

The initial display of the divs is correct. It seems that I can make the click event change the value inside the observable array without issue. The displayed divs do not change css class in response to this though.

I realize that the children of an object that is an item in an array are not, by themselves, observable. However, shouldn't my call to valueHasMutated() force the issue? This is likely also not the most elegant way to accomplish the behavior.

Anyone want to help a learning javascript guy out?

1
  • Two excellent answers, thank you! I chose Andrew's primarily because I learned a bit more about knockout from it, but both are good options. I'd use RP's method to get something to use in a more generic "anything can be chosen" scenario, but I think making it a single object is probably a better fit for my uses. Commented Oct 10, 2012 at 21:06

2 Answers 2

2

In order for the bound property to be updated, you must make the property in question observable. Also, you don't need jQuery here to handle the click event, you can use the event binding to accomplish that:

function item(options) {
    var self = this;
    this.title = ko.observable(options.title);
    this.level = ko.observable(options.level);
    this.chosen = ko.observable(options.chosen);
    this.toggleItem = function () {
        self.chosen(!self.chosen());
    };
}

function myViewModel() {
    var self = this;
    self.Tags = ko.observableArray([
        new item({
        title: 'Tag1',
        level: 'Primary',
        chosen: true
    }),
        new item({
        title: 'Tag2',
        level: 'Primary',
        chosen: false
    }),
        new item({
        title: 'Tag3',
        level: 'Primary',
        chosen: false
    }),
        new item({
        title: 'Tag4',
        level: 'Primary',
        chosen: false
    }),
        new item({
        title: 'OtherTag',
        level: 'Secondary',
        chosen: false
    })]);


    self.PrimaryTags = ko.computed(function() {
        return ko.utils.arrayFilter(this.Tags(), function(tag) {
            return tag.level() === 'Primary';
        });
    }, self);
    self.SecondaryTags = ko.computed(function() {
        return ko.utils.arrayFilter(this.Tags(), function(tag) {
            return tag.level() === 'Secondary';
        });
    }, self);

}

var vm = new myViewModel();
ko.applyBindings(vm);

Example: http://jsfiddle.net/andrewwhitaker/RepnY/1/

Sign up to request clarification or add additional context in comments.

Comments

2

observableArrays only track the array itself (items being added/removed, etc.). You would likely want to make the chosen property observable and then add a function to toggle it.

Sample here: http://jsfiddle.net/rniemeyer/7aVVy/

From your example, your markup might look like:

<div data-bind="foreach: PrimaryTags" class='tag-grid'>
    <span class="tag-cell" data-bind="text: title, css: { chosen: chosen }, click: $parent.toggleChosen">
    </span>
</div>​

with your view model like:

function MyViewModel() {
    var self = this;
    self.Tags= ko.observableArray([
        {
        title: 'Tag1',
        level: 'Primary',
        chosen: ko.observable(true)},
    {
        title: 'Tag2',
        level: 'Primary',
        chosen: ko.observable(false) },
    {
        title: 'Tag3',
        level: 'Primary',
        chosen: ko.observable(false)},
    {
        title: 'Tag4',
        level: 'Primary',
        chosen: ko.observable(false)},
    {
        title: 'OtherTag',
        level: 'Secondary',
        chosen: ko.observable(false)}]);

    self.toggleChosen = function(tag) {
        tag.chosen(!tag.chosen());  
    };

    self.PrimaryTags = ko.computed(function() {
        return ko.utils.arrayFilter(self.Tags(), function(tag) {
            return tag.level === 'Primary';
        });
    });
    self.SecondaryTags = ko.computed(function() {
        return ko.utils.arrayFilter(self.Tags(), function(tag) {
            return tag.level === 'Secondary';
        });
    });
}

Comments

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.