Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject jQuery Template with Knockout bindings

At first, I have a Button addTemplate that will add html to my body via Knockout and jQuery:

<button data-bind="click: addTemplate">Add Template</button>

<script type="text/html" id="MyTemplate">
    <div id="container">
        <a href="#" data-bind="click: $root.doAlert">Do Alert</a>
    </div>
</script>

The added Template has some knockout Bindings, too. They should activate an Alert in my ViewModel:

function MyViewModel()
{
    self = this;

    self.addTemplate = function () {
        $($("#MyTemplate").html()).appendTo("body");
    }

    self.doAlert = function() {
        alert('Hello World');
    } 
}

ko.applyBindings(new MyViewModel());

When I click on the Link in my added Template, the doAlert function does nothing. I do not want to use string-chained HTML Templates in my ViewModel.

Here is the Fiddle: http://jsfiddle.net/tgu8C/5/

like image 484
Simon Avatar asked Nov 28 '25 16:11

Simon


1 Answers

You should apply binding to newly added element.

var newElement = $($("#MyTemplate").html()).appendTo("body");
ko.applyBindings(self, newElement);  

JSFiddle DEMO

like image 70
Ilya Avatar answered Nov 30 '25 23:11

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!