淘汰js,将新项目添加到数组中 [英] knockout js, add new item to an array

查看:113
本文介绍了淘汰js,将新项目添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



敲出js,为数组添加额外的元素



基本上我有一个应用程序,用户填入某些数据,然后点击下一步,并将其添加到数组中。然而,我想要做的是在用户开始使用应用程序之前向数组中添加一些项目(这些项目是从数据库中获得的)。这个想法是,他们在开始时可以查看数组中的每个项目,然后选择一个项目并编辑该项目。我有一种感觉,我失去了一些非常明显的东西,但我似乎无法解决它。

解决方案

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

这篇关于淘汰js,将新项目添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆