knockout javascript foreach binding

我只是一个虾纸丫 提交于 2019-12-22 10:55:08

问题


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.


回答1:


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/




回答2:


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('');
    }
};


来源:https://stackoverflow.com/questions/10099657/knockout-javascript-foreach-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!