简体   繁体   中英

knockout javascript foreach binding

I'm trying to allow a user to create a casting and add an array of categories to this casting object. I was trying to use knockout's foreach binding to the array of categories and let users add new categories to the casting. I have created a jsfiddle to illustrate what I'm trying to explain here.
http://jsfiddle.net/msell/ueNg7/16/

The JSON object gets built up correctly as a user modifies a casting, but I cant quite get the list of castings to display.

You have several problems:

You are using Knockout 1.2.1

The foreach binding was not added until Knockout 2.0.

You are not using an observableArray

You need to modify your categories property to be a ko.observableArray() , instead of just an empty array. Otherwise Knockout will not be able to observe when you push to it, and the remove method will not exist.

Your this binding is wrong.

When called from event handlers, this will be set incorrectly. You can fix this in various ways, discussed in length in the Knockout documentation , but one easy fix is to change the references to viewModel instead of to this .


To fix all these, you should upgrade to Knockout 2.0, and change your view model declaration to be

var viewModel = {
    name: ko.observable(''),
    description: ko.observable(''),
    categories: ko.observableArray(),
    categoryToAdd: ko.observable(''),

    removeCategory: function(category) {
        viewModel.categories.remove(category);
    },

    addCategory: function() {
        viewModel.categories.push(new Category(viewModel.categoryToAdd()));
        viewModel.categoryToAdd('');
    }
};

Here is a corrected JSFiddle: http://jsfiddle.net/ueNg7/19/

You need to use ko.observableArray for you array otherwise Knockout wont know when you change your array and wont update, also you should use a template instead, read here http://knockoutjs.com/documentation/template-binding.html#note_2_using_the_foreach_option_with_a_named_template

var viewModel = {
    name: ko.observable(''),
    description: ko.observable(''),
    categories: ko.observableArray([]),
    categoryToAdd: ko.observable(''),
    removeCategory: function(category) {
        this.categories.remove(category);
    },

    addCategory: function() {

        this.categories.push(new Category(this.categoryToAdd()));
        this.categoryToAdd('');
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM