0

I am using the knockout postbox plugin to follow the pub sub pattern in knockout. I am able to receive and send data between components but the issue is that I am not able to use the transform functionality.

Below is the code and the fiddle link..can someone please tell me what I am doing wrong here

  <div id="container1">
        First View Model:
      <input type="text" data-bind="value: data1">      

    </div>
    <br/>
     <div id="container2">
     Second View Model:
       <span data-bind="text: data2"></span><br/>
        <span data-bind="text: newData"></span>
    </div> 

and here is my model

function Container1ViewModel()
{
    var self = this;
    self.data1 = ko.observable(false).publishOn("showDiv"); 

} 
function Container2ViewModel() {
    var self = this;
    this.data2 = ko.observable().subscribeTo("showDiv", true,transform);
    this.newData = ko.observable('45');
    var transform = function(newValue) {
    newData(newValue);
    return 123;
};

}


var container1VM;
var container2VM;

        container1VM = new Container1ViewModel();
        ko.applyBindings(container1VM, document.getElementById("container1"));

        container2VM = new Container2ViewModel();
        ko.applyBindings(container2VM, document.getElementById("container2"));

Here is the fiddle link Fiddle

What I am looking for here is that to set a value of another observable through the subscriber observable by using the transform function so I can transform the data and assign it.

Thanks

SP1
  • 1,182
  • 3
  • 22
  • 47

1 Answers1

0

You forgot some references to self and also misplaced the definition of the transform function in the second ViewModel.

function Container2ViewModel() {
    var self = this;

    var transform = function(newValue) {
        self.newData(newValue);

        // this will ALWAYS be the value passed to self.data2
        return 123;
    };

    self.newData = ko.observable('47');
    self.data2 = ko.observable().subscribeTo("showDiv", true, transform);
}

I updated the fiddle with a working version of the code: http://jsfiddle.net/0454h205/304/

Please note that always returning "123" in the transform makes it so that the data2 observable is always "123".

Pedro
  • 182
  • 5
  • 13