knockout js, add new item to an array

2019-09-14 19:34发布

问题:

So this follows on from my previous question:

knockout js, add additional elements to an array

Basically I have an app where a user fills in certain data, clicks next and this is added to an array. However, what I'd like to do is add some items into the array before the user even begins using the app (these items I get from a database). The idea being that at the start they can view each item in the array and then choose and an item and edit this item. I've got a feeling I'm missing something blindingly obvious but I cannot seem to figure it out

回答1:

Knockout observable arrays have equivalent functions to native JavaScript arrays. See: http://knockoutjs.com/documentation/observableArrays.html

So you need just to use arr.pop(item) or arr.push(item).

In case you need to replace all items and want to avoid multiple events to raise, use observableArray.valueWillMutate() and valueHasMutated() functions. See sample where I do swap the entire array:

ko.observableArray.fn.replaceWith = function (valuesToPush) {
		// NOTE: base on - ko.observableArray.fn.pushAll
		var underlyingArray = this();
		var oldItemcount = underlyingArray.length;

		this.valueWillMutate();

		// adding new items to obs. array
		ko.utils.arrayPushAll(underlyingArray, valuesToPush);

		// removing old items (using KO observablearray fnc.)
		if (oldItemcount > 0)
			this.removeAll(underlyingArray.slice(0, oldItemcount));

		this.valueHasMutated();

		return this;  //optional
	};