且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

淘汰js,将新项目添加到数组中

更新时间:2023-11-28 18:13:16

Knockout observable数组有与原生JavaScript数组相当的功能。请参阅: http://knockoutjs.com/documentation/observableArrays.html



所以你只需要使用arr.pop(item)或arr.push(item)。

如果你需要替换所有项目,并希望避免多个事件引发,请使用observableArray.valueWillMutate()和valueHasMutated()函数。请参阅示例,我将交换整个数组:

ko.observableArray.fn .replaceWith = function(valuesToPush){//注意:基于 - ko.observableArray.fn.pushAll var underlyingArray = this(); var oldItemcount = underlyingArray.length; this.valueWillMutate(); //添加新物品到obs。数组ko.utils.arrayPushAll(underlyingArray,valuesToPush); //删除旧项目(使用KO observablearray fnc。)if(oldItemcount> 0)this.removeAll(underlyingArray.slice(0,oldItemcount)); this.valueHasMutated();返回这个; //可选};


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

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