내가 매핑 플러그인을 사용하고 여기에이 목적을 위해 녹아웃 뷰 모델 에 매핑 내 서버 모델을 얻을 수있는 가장 좋은 방법을 찾고 있어요,가장 좋은 방법 - 녹아웃
아이디, 제목 사람들은 여기에있는 groupViewModel과 비슷한 것으로 매핑되었습니다. 이 매핑을 항상 새로운 groupViewModel에 정확하게 캐스트하도록하려면 어떻게해야합니까? 여기 실제 문제는 입니다. Id, Title, People은 보기가 아니라 addPerson 방법, 이 해결 방법 또는 정확하고 단순하면서도 정확하게 매핑 할 수있는 가장 좋은 방법을 알려주십시오. 고마워.
여기서 우리의 viewModel에는 그룹 배열이 포함되어 있습니다.이 그룹 배열을 GroupViewModel 항목으로 변환하는 방법은 질문에 대해 이렇게 대답 할 수 있습니다. -
var model = @Html.Raw(Json.Encode(Model));
$(function() {
var root = this;
var viewModel = ko.mapping.fromJS(model, root);
// there are Groups as expected but not the addPerson
// will cause undefined exception
var groupViewModel = function (item) {
var self = this;
self.Id = ko.observable(item.Id);
self.Title = ko.observable(item.Title);
self.People = ko.observableArray([]);
self.addPerson = function (name) {
console.log('addPerson Clicked');
}; // .bind(self)
}
ko.mapping.fromJS(viewModel);
ko.applyBindings(viewModel);
});
편집이 대답에 기반 업데이트 :
서버의 ViewModel 클라이언트의
In Server we have this :
class ServerVm {
public int Id { get; set; }
public IList<GroupMap> Groups { get; set; } // groupViewModel
}
우리는이 :
var model = @Html.Raw(Json.Encode(Model));
$(function() {
var root = this;
var viewModel = ko.mapping.fromJS(model, root);
//viewModel.Groups = ko.observableArray([]);
// No need because it's same as server model
viewModel.addGroup = function (teamName) {
console.log('addGroup Clicked');
}; // .bind(self)
// addGroup is fine
// it's defined here and working fine, no special mapping needed here
// "model" contains something
var groupViewModel = function (item) {
var self = this;
self.Id = ko.observable(item.Id);
self.Title = ko.observable(item.Title);
self.People = ko.observableArray([]);
// self.addPerson - this is hidden in the "model"
self.addPerson = function (name) {
console.log('addPerson Clicked');
}; // .bind(self)
}
ko.mapping.fromJS(viewModel);
ko.applyBindings(viewModel);
});
우리의 문제는 내부에있는 self.addPerson
입니다 우리의 중첩 컬렉션 becau 컨테이너 (groupViewModel)가 GroupMap에 자동으로 바인드되지 않습니다. 때마다, 당신은 documentation에서 3 개 매개 변수를 ko.mapping.fromJS
방법의 다른 오버로드를 사용할 수
감사합니다 일리아 나는 차이점을 이해하기 위해 코드를 자세하게보고 있지만 두 번째 방법은 내 것과 정확히 동일하다고 말해야합니다. 여기서 코드 추출을 게시했습니다. VM = ko.mapping .JS (데이터); 그런 다음 vm.Addsomething, 이것은 내 것과 동일합니다. vm.addGroup이 있습니다. 내 groupViewModels 각각에 addPerson이 있어야 할 때 내부 객체에 대한 문제입니다. 내 게시물을 편집하여 의미를 나타냅니다. – LastBye
동일하지 않습니다. , 적어도 현재의 질문과 같은 것은 아닙니다. 하지만 당신이 가진 문제를 이해하기 시작했다고 생각합니다. –
고마워요. 여기에 게시하려면 5 분만주세요. – LastBye