Knockout javascript foreach binding

I am trying to allow the user to create a casting and add an array of categories to this cast object. I tried to use the foreach knockout binding to an array of categories and allowed users to add new categories to the cast. I created jsfiddle to illustrate what I am trying to explain here.
http://jsfiddle.net/msell/ueNg7/16/

The JSON object is created correctly as the user modifies the casting, but I cannot get a list of readings.

+3
source share
2 answers

You have a few problems:

You are using Knockout 1.2.1

The foreach binding was not added until the 2.0 knockout was released.

You are not using observableArray

You need to change the categories property as ko.observableArray() instead of a simple array. Otherwise, the knockout will not be able to observe when you push to it, and the remove method will not exist.

The binding of this is incorrect.

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


To fix all this, you must go to "Knockout 2.0" and change your view model ad to

 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 the adjusted JSFiddle: http://jsfiddle.net/ueNg7/19/

+10
source

You need to use ko.observableArray for your array, otherwise Knockout will not know when you will change your array and will not update it, you should also 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(''); } }; 
0
source

Source: https://habr.com/ru/post/910451/


All Articles