javascript - Understanding how nested components binding works on KnockoutJS -
i'm trying use knockout components, , 1 thing i'm trying use nested components this:
<parent-component params="parenttext: parenttext"> <child-component params="childtext: childtext"></child-component> </parent-component> parenttext , childtext both members of same view model object, when run following error:
uncaught referenceerror: unable process binding "template: function (){return { nodes:$componenttemplatenodes} }" message: childtext not defined
this sample i'm trying run:
var parentcomponent = function(params) { var self = this; self.parenttext = params.parenttext; }; ko.components.register('parent-component', { viewmodel: parentcomponent, template: '<div><p><strong data-bind="text: parenttext"></strong></p><!-- ko template: { nodes: $componenttemplatenodes } --><!-- /ko --></div>' }) var childcomponent = function(params) { var self = this; self.childtext = params.text2; }; ko.components.register('child-component', { viewmodel: childcomponent, template: '<p data-bind="text: childtext"></p>' }) var viewmodel = function() { var self = this; self.title = 'knockoutjs component test'; self.parenttext = 'this text1'; self.childtext = 'this text2'; }; ko.applybindings(new viewmodel(), document.getelementbyid('content')); <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div id="content"> <h1 data-bind="text: title"></h1> <parent-component params="parenttext: parenttext"> <child-component params="childtext: childtext"></child-component> </parent-component> </div> can please explain me i'm doing wrong?
thanks,
your doing good. can see 2 problems here though.
first:
$componenttemplatenodes not seen in case because using knockout 3.2 in not being supported yet, better update lib newer one, knockout 3.4 out $componenttemplatenodes support starts @ 3.3.
second:
in childcomponent vm referred params text2
self.childtext = params.text2;
but when declared in html binding, names childtext.
<child-component params="childtext: childtext"></child-component>
and take note <child-component params="childtext: childtext"></child-component> enclosed in inner component childtext cannot seen here, shoud refer $root.childtext.
to sum up: binding should be.
<parent-component params="parenttext: parenttext"> <child-component params="childtext: $root.childtext"></child-component> </parent-component>
and childcomponent vm should be:
self.childtext = params.childtext;
Comments
Post a Comment