knockout.js - Knockout Subscribe to any change in observable complex object -


i have viewmodel contains observable, initialized object. object contains observables.

my goal notified whenever object changes (or: when observable in object changes)

jsfiddle

complex object:

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

viewmodel

ns.mainvm = function () {    var simpleobject = ko.observable('i pretty simple');     simpleobject.subscribe(function (newvalue) {        document.getelementbyid('simplesubscribtionfeedback').innertext = newvalue;    });     var complexobject = ko.observable(ns.complexobj());    complexobject.subscribe(function (newvalue) {        // react change in complex object        document.getelementbyid('complexsubscribtionfeedback').innertext = 'i dont executed :(';    });     return {        simpleobject: simpleobject,        complexobject: complexobject    }; }; 

binding

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

is there possiblity react on changes on complex object? appreciated.

i tried dirtyflag solutions (link in comments), rpniemeyer. problem dirty flag on complex object is, when switches "true" , i'm hooking subscription of flag, thats ok first time. react further changes, need set dirtyflag false again (after doing stuff in subscription). lead subscription loop.

you can use following trick:

ko.computed(function() {     return ko.tojson(complexobject); }).subscribe(function() {     // called whenever of properties of complexobject changes }); 

see http://jsfiddle.net/xcajt4qn/3/

the reason why works ko.tojson recursively read properties in object, therefore making computed depend on properties.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -