Why knockout binding isn't working on the following code
ko.components.register('like-widget', {
template: "<input data-bind=\"value: firstName\" />"
});
ko.applyBindings()
$('#btnAdd').on('click', function() {
var $newWidget = $('<like-widget>');
$('#addZone').append($newWidget);
ko.applyBindings({ firstName: ko.observable("Bert") }, $newWidget[0]);
});
The approach you've chosen (using jQuery), isn't very "knockout-like". Still it can be done:
In your html markup, you need to explicitly tell knockout which parameters to use in the component's viewmodel (use params=""
)
ko.components.register('like-widget', {
template: "<input data-bind=\"value: firstName\" />"
});
ko.applyBindings({})
$('#btnAdd').on('click', function() {
var $newWidget = $('<like-widget params="firstName: firstName">');
$('#addZone').append($newWidget);
ko.applyBindings({
firstName: ko.observable("Bert")
}, $newWidget[0]);
});
<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 id="addZone"></div>
<button id="btnAdd">add</button>
My suggestion however, is to use a click
binding and an observableArray
of widget viewmodels.
var components = ko.observableArray([]);
var addComponent = function() {
components.push({
firstName: "Bert"
});
}
ko.components.register('like-widget', {
viewModel: function(params) {
this.firstName = ko.observable(params.firstName || '');
},
template: "<input data-bind=\"value: firstName\" />"
});
ko.applyBindings({
components: components,
addComponent: addComponent
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: components">
<like-widget params="firstName: firstName" />
</div>
<button data-bind="click: addComponent">add</button>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments