Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node,express,jade rendered pages doesn't data-bind with knockout.js

I'm running a Node server with express which renders jade. I'm trying to make my client side use knockout.js but the view never updates... I don't get any errors in the console and I just can't figure out what is wrong.

Page:

extends layout

    block content

    script(src='knockout/knockout-2.2.1.debug.js', type='text/javascript')
    script(src='js/app.js', type='text/javascript')

    p Hi,
        strong(data-bind="text: firstName")

rendered html:

<!DOCTYPE html>
<html>
    <head>
    <link rel="stylesheet" href="/stylesheets/style.css">
    </head>
    <body>
        <script src="knockout/knockout-2.2.1.debug.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>

        <p>Hi,<strong data-bind="text: firstName"></strong></p>

    </body>
</html>

app.js:

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}

ko.applyBindings(new AppViewModel());

is there something I'm missing here or is it just not possible to make this happen with Node.js and express?

like image 886
Moriya Avatar asked Jun 25 '26 17:06

Moriya


1 Answers

You need to make sure you call ko.applyBindings() after the DOM has already been loaded.

Either wrap the code in app.js in window.onload, in jQuery's ready() function, or move your script tag to be below <p>Hi,<strong data-bind="text: firstName"></strong></p>.

like image 95
go-oleg Avatar answered Jun 27 '26 07:06

go-oleg



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!