Question

I have observable variable:

var mouse = ko.observable({
    x: ko.observable(),
    y: ko.observable()
});

I want subscribe event of mouse to be called when either x or y changes:

mouse.subscribe(function(){
    alert('changed');
});

mouse().x(5);
mouse().y(7);

But it does not. Can you suggest anything?

Was it helpful?

Solution

You can add this:

mouse().x.subscribe(function () { mouse.valueHasMutated() });

http://jsfiddle.net/nyothecat/x9MWp/

Or even better:

for (var prop in mouse()) {
    if (ko.isObservable(mouse()[prop])) mouse()[prop].subscribe(function () { mouse.valueHasMutated() });
}

http://jsfiddle.net/nyothecat/x9MWp/1/

OTHER TIPS

Create a computed observable that is a function of both x and y:

self.mousePos = ko.computed(function() {
    return self.x() + self.y();
});

Then subscribe to mousePos.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top