javascript - How to Change viewmodel's data after binding a knockout template to a custom component -


i have static template binding custom component in knockoutjs. viewmodel data initialized , working fine (getting john smith in output).

$(document).ready(function() {    var viewmodel = function() {      this.name = ko.observable('john smith');    }    var viewmodelobject = new viewmodel();      ko.components.register('my-component', {      viewmodel: viewmodel,      template: 'name: <input data-bind="value: name" /> '    });      viewmodelobject.name('smith john');    ko.applybindings(viewmodelobject);  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>  <div>    <my-component></my-component>  </div>

jsfiddle: http://jsfiddle.net/17cmjptl/1/

here, trying change value in viewmodel. know there know use of passing viewmodelobject ko.applybindings method. tried.

can on, how change viewmodel data without rebinding. ?

ie. want output smith john.

i think misunderstand how components intended used. components way custom elements own internal behavior. interact components via parameters, not directly controlling components viewmodel.

first, let's @ going on code. correctly create constructor function component viewmodel, , register component. function run every time component instantiated: each component own instance of object.

then construct own instance of viewmodel, set name, , bind it. knockout creates instance of component because custom element exists, no parameters on it. constructor function run, getting default name, , bound input. viewmodel called applybindings not used anything, because component got own instance of viewmodel.

what want create viewmodel passes name component via params. can control viewmodel, in turn affect component. might this

var componentvm = function (params) {     this.name = params.name; }  ko.components.register('my-component', {     viewmodel: componentvm,     template: 'name: <input data-bind="value: name" /> ' });  var vm = {     name: ko.observable("john smith"),     updatename: function() {          this.name("smith john");        } }; ko.applybindings(vm);  <div>     <my-component params="name: name"></my-component>     <button data-bind="click: updatename">update</button> </div> 

here fiddle can play with.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -