Hayden Crocker
Hayden Crocker

Reputation: 529

Knockout js dynamic bindings

I have the following javascript defined page in my application and I'm trying to use knockout within it.

var dashboard = new DashboardPage();

function DashboardPage() {
    var page = this;

    page.open = function () {
        var bindingString = '{ name: "dashboard-template" }';
        $('#main div').html("").attr("data-bind", bindingString);
        ko.applyBindings(new page.ViewModel(), $("#main")[0]);
    };

    page.ViewModel = function () {
        var self = this;
        self.content = ko.observable("SOME WORDS");
    };
    //Other code removed.

This is the template:

<script type="text/html" id="dashboard-template">
    <div id="wrapper-block2" class="wrapper-block">
        <div id="content-block2" class="content-block">
            Hello
        </div>
    </div>
    <div id="wrapper-block3" class="wrapper-block">
        <div id="content-block3" class="content-block">
            World
        </div>
    </div>
</script>

dashboard.open() is definitely being called, but my #main div is not being populated and there are no errors.

Could someone point out what I'm doing wrong? I assume as there is no error that ko is not even trying to bind anything.

Upvotes: 0

Views: 260

Answers (2)

chrisjsherm
chrisjsherm

Reputation: 1329

You need to specify the "template" parameter in your data-bind, and I also think the ordering of your functions may be a bit screwy. I think this is what you're looking for:

HTML:

<div id="main" data-bind="template: { name: 'dashboard-template' }"></div>

<script type="text/html" id="dashboard-template">
    <div id="wrapper-block2" class="wrapper-block">
        <div id="content-block2" class="content-block" data-bind="text: content">
        </div>
    </div>
</script>

JS:

function DashboardViewModel() {
    var self = this;

    self.content = ko.observable("SOME WORDS");
};


$(document).ready(function () {
    ko.applyBindings(new DashboardViewModel(), $("#main")[0]);
});

Upvotes: 0

Paul Manzotti
Paul Manzotti

Reputation: 5147

Aren't you supposed to use the word template when you are binding a template?

var bindingString = 'template: { name: "dashboard-template" }';

Upvotes: 1

Related Questions