Reputation: 4719
Having a look at knockout js and the mapping plugin. I noticed that if I pass an object, I cannot subscribe to it for changes. Basically, I want to be notified if any member of the object changes. I don't really care to get back the attribute that changed (but if it is possible would like to know how)
function EventsKoModel(data){
var self = this;
self.event = ko.mapping.fromJS(data);
//the below throws Error
//TypeError: self.event.subscribe is not a function
self.event.subscribe(function(){
console.log("something changed");
});
}
var data = {
'id': 14124124124124,
'name': 'Some Event',
'events': [{
'id': 1
},{
'id': 2
}]
}
var d = new EventsKoModel(data);
ko.applyBindings(d);
However, if I pass an array with objects, it works I saw that when passing an object to fromJS, the returned object does not have a subscribe method Is there anyway to work around this?
Thanks
Upvotes: 1
Views: 2069
Reputation: 1036
I had the same requirements a while back and wrote Knockout Reactor for this. It does a good job at subscribing to hierarchical models and provides most of the functionality you might need to get you going right away.
Here's the link to it:
https://github.com/ZiadJ/knockoutjs-reactor
Upvotes: 0
Reputation: 453
Assuming you want the subscriber to fire each time the event
is updated including the first time it gets set. You could try this;
function EventsKoModel(data){
var self = this;
self.event = ko.observable();
self.event.subscribe(function(){
console.log("something changed");
});
ko.mapping.fromJS(data, {}, self);
}
Upvotes: 1