Redacted question and example
I'm trying to get Knockout components to bind after the initial ko.applyBindings();
so I can add custom elements dynamically.
In my original post I referred to loading content by ajax, but my problem occurs when custom elements are added to the DOM using something like jQuery append
.
Here's an example:
$(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>
Original post
I've successfully created my new component, <mynew-widget></mynew-widget>
I've seen the joy of peppering my page with them and everything works beautifully... until I load new content (an AJAX-loaded modal popup, for example) which contains <mynew-widget></mynew-widget>
. Nothing happens.
Is this a limitation of Knockout or have I wired things up incorrectly?
Please tell me it's the latter - as I love not having to worry about when/where to call ApplyBindings and on which parts of the DOM.
Thinking it through, I understand knockout needs to notice that the custom elements have been added to the DOM - but I was hoping it might just work in a jQuery '$().on(...)
' kind of way.