knockout js, add new item to an array

本秂侑毒 提交于 2019-12-25 09:37:21

问题


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
	};


来源:https://stackoverflow.com/questions/43920118/knockout-js-add-new-item-to-an-array

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