Search code examples
knockout.jsknockout-3.0

Two way binding between components in Knockoutjs


I'm looking to create reusable component, I'm just not able to create the two way binding I need without a external library such as the postbox sub/pub I've seen.

Here is an example codepen of what I am trying to do

It's a very basic example but it shows what I need.

The mainViewModel has a property name which I need to get from the name-input component.

I'm used to angular 2+ and using two way bindings, does KO have something similar?

Thanks

Steve

Edit: Javascript:

ko.components.register("name-input", {
  viewModel: function(params) {
    var self = this;
    self.userInput = ko.observable();
    return self;
  },
  template: "<div><input data-bind='textInput: userInput' placeholder='Enter your name'><br/>Hello,<span data-bind='text:userInput'></span></div>"
});


function mainViewModel() {
  var self = this;

  self.name = ko.observable();
}

ko.applyBindings(new mainViewModel(), $("#main")[0]);

Html:

<body>
  <div id="main">
    <div id="inner-container">
      MyName:
      <div data-bind="text:name"></div>
    </div>
    <name-input></name-input>
  </div>
</body>

Solution

  • You can use the params attribute to pass an observable reference for the component instance to read from and write to:

    <name-input params="value: name"></name-input>
    

    In your component's viewmodel function, you reference this value instead of creating a new observable:

    function(params) {
      var self = this;
      self.userInput = params.value;
      return self;
    }
    

    Running example in a fork of your Codepen