Reputation: 1198
I know how to bind an anchor element to a click event. But I am unsure how to do it when the anchor elements are being loaded in via the HTML binding event. Here is my code:
<a href='/my_page' data-bind="click:$root.loadPage">Click here to load</a>
** This anchor element serves HTML from the server. Within the served HTML, I have some anchor elements I want to bind to a similar function. But what I am doing is not working. Here is my knockout code that does the "loadPage"
this.loadPage = function(data,object)
{
self.showLoadingIndicator();
$.get(object.target.href, function(response)
{
self.pageData(response.html);
}, 'json');
}
** I have an observable setup called "pageData" that serves the HTML content to the page.
My problem is: In my "served" HTML, I have the the same exactly click binding set on some of the HTML objects here, but they don't fire the event...
Any solutions?
Thanks in advance!
Rob
Upvotes: 0
Views: 662
Reputation: 3192
When you call applyBindings, it only affects things that are already on the page - it does not affect anything that is loaded later.
However, you can call applyBindings again on a new chunk of markup that is added to the page.
var viewmodel = ...;
ko.applyBindings(viewmodel);
this.loadPage = function(data,object)
{
self.showLoadingIndicator();
$.get(object.target.href, function(response)
{
self.pageData(response.html);
var newStuffAddedToDOM = ...;
ko.applyBindings(viewmodel, newStuffAddedToDOM);
}, 'json');
}
Here's a working fiddle: http://jsfiddle.net/tlarson/65K3u/
Upvotes: 0