为什么淘汰赛绑定不适用于以下代码
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]);
});
答案 0 :(得分:2)
您选择的方法(使用jQuery),并非像&#34;类似于淘汰赛&#34;。仍然可以做到:
在你的html标记中,你需要明确告诉knockout在组件的viewmodel中使用哪些参数(使用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]);
});
&#13;
<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>
&#13;
我的建议是使用click
绑定和observableArray
小部件视图模型。
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
});
&#13;
<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>
&#13;