简体   繁体   中英

How to subscribe to observable in the parent model from a component in knockout.js

I am working with some legacy code that uses Knockout.js and I have to add a new functionality and I am a bit lost at one point. I can not share the actual code so I will use some pseudo code to describe my problem

Assume I have some sample View model

function ViewModel(params) 
  {
    this.questions = params.questions;
    this.clear = ko.observable();
  }

which gets an array of questions from external source but it is not an observable array. I also have a function in the View model which populates the clear() observable

ViewModel.prototype.add = function()
{
  if (this.clear === 'No'){
    this.clear('Yes');
   } else{
    this.clear('No');
   }
}

I have a registered component

ko.components.register('customComponent', {
  viewModel: function(params) {
    this.clearInComponent = ko.observable(params.clear);
  },
  template: '<div data-bind="text: clearInComponent "></div>'
});

Now in my HTML I have a button which on click sets some value to cthe clear() observable and the component where I am passing the parameters from the View model

<button data-bind="click: add"></button>

<questionnaire params="questions: questions, clear:clear"></questionnaire>

Now whenever the value of clear() in the parent ViewModel is changed it is reflected as well in the component which is expected. What I want to achieve is to set a subscription to clearInComponent so when the clear() observable in the parent View model changes I would be able to catch the event and do some additional things. I tried to add subscription to clearInComponent in the component View model but it does not work.

this.clearInComponent.subscribe = function(newValue){
   // do stuff
}

My question is if that is possible and how I can do it? Thanks in advance.

I think this might be the issue:

this.clearInComponent = ko.observable(params.clear);

Since params.clear is itself an observable, you're basically wrapping an observable in another observable, making subscribing to this.clearInComponent useless since its value will never mutate.

Instead, just use params.clear directly:

this.clearInComponent = params.clear;

this.clearInComponent.subscribe(function (newValue) {
    // this should work fine...
    console.log(newValue);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM