@shyann
In knockout.js, you can subscribe to an observable in the parent model from a component by passing the parent model as a parameter to the component and then accessing the parent model's observable from within the component.
Here's an example:
1 2 3 |
function ParentModel() { this.parentObservable = ko.observable('Initial value'); } |
1 2 3 4 5 6 7 8 9 10 11 12 |
ko.components.register('my-component', { viewModel: function(params) { this.parentModel = params.parentModel; this.subscribeToParentObservable = function() { this.parentModel.parentObservable.subscribe(function(newValue) { console.log('Parent observable changed to: ' + newValue); }); }; }, template: '<button data-bind="click: subscribeToParentObservable">Subscribe to parent observable</button>' }); |
1
|
<div data-bind="component: { name: 'my-component', params: { parentModel: $root } }"></div> |
In this example, the component subscribes to the parent model's parentObservable
property and logs a message whenever the value of the observable changes. You can further extend this example to perform any actions based on the changes in the parent model's observable.