What is the best way of cloning/copying an observablearray in knockoutJS?

馋奶兔 提交于 2019-12-17 23:36:26

问题


Question says it all really. I want to copy an observable array to another in KnockoutJS.


回答1:


To clone an observableArray you would want to do:

var viewModel = {
    array1: ko.observableArray(["one", "two"]),
    array2: ko.observableArray()
};

viewModel.clone = function() {
   viewModel.array1(viewModel.array2.slice(0));
};

If you want to just do a copy, then you would do:

viewModel.array1(viewModel.array2());

The problem with the second example is that the underlying array is the same, so pushing to array1 or array2 would result in both having the new value (as they both point to the same array).




回答2:


I was faced with the same task; to clone an observable array. The only way I could figure out how to do it, is to convert the observable to an JS object, then convert that object to an observable object. The following function requires KnockoutJS mapping plugin: http://knockoutjs.com/documentation/plugins-mapping.html

function cloneObservable(observableObject) {
    return ko.mapping.fromJS(ko.toJS(observableObject));
}

Hope this helps




回答3:


Assuming you have something like:

modelA { someValues: observableArray(); }
modelB { iWantYourValues: observableArray(); }

You should be able to:

modelB.iWantYourValues(modelA.someValues())



回答4:


Not exactly what you're asking, but I'd like to add this for posterity...

If you want to clone an observable that stays in sync with the original (most often to create a throttled/debounced clone while maintaining the original), you can do something as such:

const clone = ko.pureComputed(() => original()).extend({ rateLimit: 500 })



来源:https://stackoverflow.com/questions/6509297/what-is-the-best-way-of-cloning-copying-an-observablearray-in-knockoutjs

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