문제

나는 이제 꽤 많은 시간 동안 이것을 알아 듣고 싶어했습니다. 나는이 문제를 해결하는 것을 찾을 수 없었지만, 내가 틀렸다면 나를 바로 잡아주세요.

문제점 : 중첩 된 Array / Object 구조로 JSON API를 통합하는 데이터가 있습니다. 맵핑을 사용하여 모델을 데이터로 초기에 채 웁니다. 이 작업을 업데이트하려면 새 데이터가 도착하거나 기존 데이터를 업데이트하는 경우 모델을 확장하고 싶습니다.

내가 발견 한 바와 같이, 맵핑 옵션 키는 나를 위해이 속임수를해야하지만, 매핑 옵션의 기능을 오해 한 것일 수도 있습니다.

이 예제로 표현되는 문제를 삶아줌으로써

var userMapping = {
    key: function(item) {
        return ko.utils.unwrapObservable(item.id);
    }
};

// JSON call replaced with values
var viewModel = {
    users: ko.mapping.fromJS([], userMapping)
};

// Should insert new - new ID?
ko.mapping.fromJS([{"id":1,"name":"Foo"}, {"id":2,"name":"Bar"}], userMapping, viewModel.users);

// Should only update ID#1 - same ID?
ko.mapping.fromJS([{"id":1,"name":"Bat"}], userMapping, viewModel.users);

// Should insert new - New ID?
ko.mapping.fromJS([{"id":3,"name":"New"}, {"id":4,"name":"New"}], userMapping, viewModel.users);

ko.applyBindings(viewModel);​
.

fiddle : http://jsfiddle.net/mikaelbr/gdja7/

보시다시피 첫 번째 행은 데이터를 삽입합니다. 문제 없다. 그러나 업데이트하려고하면 콘텐츠를 대체합니다. 세 번째 매핑에 대해 동일합니다. 그것은 확장하는 대신 콘텐츠를 대체합니다.

나는 그것을 잘못 사용하고 있습니까? 매핑을 사용하기 전에 콘텐츠를 "수동으로"확장하려고 시도해야합니까?

편집 솔루션 :
모든 현재 모델을 저장하는 두 번째 도우미 어레이를 사용 하여이 경우를 해결했습니다. 새 데이터에서는이 배열을 확장하고 뷰 모델을 갱신하여 누적 항목을 포함합니다.

업데이트 (내 경우 WebSocket 메시지에서), 모델을 통해 반복하고, 해당 항목의 내용을 변경하고 knockout lib에 변경된 값을 알리는 방법을 사용하여 valueHasmutated ()를 사용했습니다.

도움이 되었습니까?

해결책

From looking at your example code the mapping plugin is behaving exactly as I would expect it to. When you call fromJS on a collection you are effectively telling the mapping plugin this is the new contents of that collection. For example:

On the second line, How could it know whether you were updating or whether you had simply removed id:2?

I can't find any mention of a suitable method that treats the data as simply an update, although you could add one. Mapped arrays come with some helpful methods such as mappedIndexOf to help you find particular items. If you receive an update data set simply loop through it, find the item and update it with a mapping.fromJS call to that particular item. This can easily be generalized into reusable method.

다른 팁

You can use ko.mapping.updateFromJS() to update existing values. However, it does not add new values so that would be a problem in your instance. Take a look at the link below for more details.

Using updateFromJS is replacing values when it should be adding them

Yes, you should first collect all data into a list or array and then apply the mapping to that list. Otherwise you are going to overwrite the values in your viewModel.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top