-1

I'm trying to modularize my code and as a result have a situation where I want to pass an observable from one view model into a second and have that observable bound in the context of the second view model.

Roughly what I have is:

var ModelA = function () {
    var self=this;
    self.model_b = new ModelB();
    self.my_variable = ko.observable();
    self.model_b(self.my_observable);
};

var ModelB = function () {
    var self=this;
    function passObservable( passed_observable ) {
        self.received_variable = observable;
    }
};

ko.applyBindings(new ModelA());

Then in the view, I want to bind using data-bind='text: model_b.received_variable'

========== FOLLOW UP ==========

One suggested solution was to have two independent observables, one in each viewmodel and then use the gang of four observer pattern to sync up these two observables, which can be implemented using KO's subscribable object. It feels unnecessarily heavy to have two observables when I only want one and, then to need to add the code to let these two objects communicate with one an other.

Dom
  • 2,980
  • 2
  • 28
  • 41
  • Possible duplicate of [Whats the best way of linking/synchronising view models in Knockout?](https://stackoverflow.com/questions/9892124/whats-the-best-way-of-linking-synchronising-view-models-in-knockout) – adiga Dec 07 '18 at 21:12
  • @adiga Thanks for the tip about subscribable, I'm already doing something similar, but was hoping there might be a neater solution. I'll leave this question open to see if anything else turns up. – Dom Dec 07 '18 at 21:46

1 Answers1

2

I not pretty much sure if this is how you want it but I would create structure in following way ---

use "with" binding to create context of any object and then you can access any property inside object to bind directly.

var ModelA = function () {
    var self=this;
    self.my_variable = ko.observable("val");
    self.model_b = new ModelB();
    self.model_b.setObservable(self.my_variable());// use '()' if you want to pass value OR simply use self.my_variable to pass observable ref.
    
};

var ModelB = function () {
    var self=this;
    self.received_variable;
    self.setObservable = function(passed_observable) {
        self.received_variable = passed_observable;
   }
};

ko.applyBindings(new ModelA())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- ko with:model_b -->
<span data-bind="text:received_variable"></span>
<!-- /ko -->
Amit Bhoyar
  • 1,007
  • 5
  • 20