Moriya Moriya - 3 months ago 20
Jade Question

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?

Answer

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>.