【发布时间】:2015-01-24 02:42:41
【问题描述】:
编辑的问题和示例
我试图让 Knockout 组件在初始 ko.applyBindings(); 之后绑定,以便我可以动态添加自定义元素。
在我的原始帖子中,我提到了通过 ajax 加载内容,但是当使用 jQuery append 之类的东西将自定义元素添加到 DOM 时,就会出现问题。
这是一个例子:
$(function() {
// Register a simple widget:
ko.components.register('like-widget', {
template: '<div class="alert alert-info">This is the widget</div>'
});
// Apply bindings
ko.applyBindings();
// Wire up 'add' button:
$('#btnAdd').on('click', function() {
$('#addZone').append("<like-widget></like-widget>");
});
});
<link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<body>
Here's a widget, declared inline:
<like-widget></like-widget>
<button id='btnAdd'>Add a new widget to the grey box:</button>
<br/><br/>
<div id='addZone' class="well">
Widgets will be appended here
</div>
<p>When you run this code, the widget custom element is indeed added to the box (see source) but the widget's template is not bound, so nothing appears. How do I get it to bind/appear?</p>
</body>
原帖
我已经成功创建了我的新组件<mynew-widget></mynew-widget>
我已经看到了在我的页面上添加它们的乐趣,并且一切都运行良好......直到我加载包含<mynew-widget></mynew-widget> 的新内容(例如,加载 AJAX 的模式弹出窗口)。什么都没有发生。
这是 Knockout 的限制还是我接线错误?
请告诉我是后者 - 因为我喜欢不必担心何时/在何处调用 ApplyBindings 以及在 DOM 的哪些部分。
经过深思熟虑,我知道淘汰赛需要注意自定义元素已添加到 DOM 中 - 但我希望它可能只是以 jQuery '$().on(...)' 之类的方式工作。
【问题讨论】:
-
您需要包含您正在尝试做的事情的代码示例。照原样,我们无法帮助您调试
-
以上+你可能没有正确接线
-
好的 - 已编辑和重新调整。另外 - 我知道你可能想用 KO 本身实现 btnAdd 功能,但我只想说我不想允许完全的灵活性。
标签: javascript jquery knockout.js dom-manipulation