0

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

rckehoe
  • 1,198
  • 15
  • 16
  • possible duplicate of [knockout data-bind on dynamically generated elements](http://stackoverflow.com/questions/11066732/knockout-data-bind-on-dynamically-generated-elements) – Chris Diver May 08 '13 at 16:36
  • I have seen that post before, but I cannot get the solution to work, so I can only assume it's a different problem. The 2nd param in the ko.ApplyBindings I think will work, if I can figure out what i am suppose to put here... I attempted to put the div object that the "pageData" is being binded to... – rckehoe May 08 '13 at 21:18

1 Answers1

0

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/

CodeThug
  • 3,054
  • 1
  • 21
  • 17
  • where newStuffAddedToDOM = response.html ?? Is that right? I get an error that says the 2nd param must be a DOM node... – rckehoe May 08 '13 at 17:57
  • As the error indicates, newStuffAddedToDOM needs to be a reference to a DOM node, e.g. newStuffAddedToDOM = $("#container")[0]; where "container" is the ID of the
    (or other element) that wraps the pageData content.
    – Cyanfish May 09 '13 at 01:07