2014-11-19 7 views
14

객체로 초기화되는 관측 가능 객체를 포함하는 뷰 모델이 있습니다. 이 개체 자체에 관찰 가능 항목이 포함되어 있습니다.녹아웃 관측 가능한 복잡한 객체의 변경 사항을 구독하십시오.

내 목표는 통지 될 때마다 해당 개체 변경 (또는 : 때 개체 변경의 모든 관찰) 개체

jsfiddle

복잡한 :

var ns = ns || {}; 

ns.ComplexObj = function (item) { 
    var self = this; 

    if (!item) { 
     item = {}; 
    } 

    self.id = item.Id || ''; 
    self.company = ko.observable(item.Company || ''); 
    self.email = ko.observable(item.Email || ''); 

    self.company.subscribe(function() { 
     console.log('debug: company changed'); 
    }); 

    return self; 
}; 

뷰 모델

ns.mainvm = function() { 
    var simpleObject = ko.observable('i am pretty simple'); 

    simpleObject.subscribe(function (newValue) { 
     document.getElementById('simpleSubscribtionFeedback').innerText = newValue; 
    }); 

    var complexObject = ko.observable(ns.ComplexObj()); 
    complexObject.subscribe(function (newValue) { 
     // i would like to react to any change in complex object 
     document.getElementById('complexSubscribtionFeedback').innerText = 'i dont get executed :('; 
    }); 

    return { 
     simpleObject: simpleObject, 
     complexObject: complexObject 
    }; 
}; 

var container = document.getElementById('wrapper'); 
if (container) { 
    ko.applyBindings(ns.mainvm, container); 
} else { 
    console.warn("container for binding ko not found"); 
} 

복잡한 객체의 변화에 ​​반응하여 어떤 possiblity를가 결합? 어떤 도움을 주셔서 감사합니다.

이미 rpniemeyer에서 dirtyFlag 솔루션 (주석의 링크)을 사용해 보았습니다. 복합 객체에 더티 플래그가있는 문제는 "true"로 전환하고 해당 플래그의 구독에 연결하면 처음으로 확인 만합니다. 더 많은 변화에 반응하기 위해서, 나는 dirtyFlag를 false로 다시 설정할 필요가있다. 가입 루프로 연결됩니다.

ko.computed(function() { 
    return ko.toJSON(complexObject); 
}).subscribe(function() { 
    // called whenever any of the properties of complexObject changes 
}); 

따라서 모든 속성의 계산 의해 좌우하고, http://jsfiddle.net/xcajt4qn/3/

ko.toJSON 재귀 적 객체의 모든 속성을 읽을 것입니다 작동하는 이유를 참조하십시오

+0

[이 게시물] (https://roysvork.wordpress.com/2014/01/12/tracking-changes-to-complex-viewmodels-with-knockout-js/)로 시작될 수 있습니다. 귀하의 의견에 – Michael

+0

주셔서 감사합니다! 나는 내 질문을 편집했다. –

+1

이 플러그인은 정확하게 네가하는 일을하는 것처럼 보입니다. https://github.com/ZiadJ/knockoutjs-reactor – Domysee

답변

29

당신은 다음과 같은 트릭을 사용할 수 있습니다 .

+2

감사합니다. –

+3

당신은이 속임수를 찾는 것에 화가났습니다. 그러나 또한 굉장한. – kernel

+4

객체의 * 비 * 관찰 가능 속성이 변경 될 때마다 호출된다는 점에 유의하십시오. 이는 바람직하지 않을 수 있습니다. – tloflin

관련 문제