Reputation: 344
I am trying the simplest possible example of knockout.js but it doesn't work (first and last names stay empty). I put my script tags after html tags that use binding and call ko.applyBindings after page loads. Alert works so the function fires. Any help?
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script type="text/javascript' src='js/knockout-3.4.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function AppViewModel() {
alert("b");
this.firstName = "Bert";
this.lastName = "Bertington";
}
$(window).load(function() {
ko.applyBindings(new AppViewModel());
});
</script>
EDIT This problem is solved, but I have another one. What to do if I wanted to add first and last name simultaneously after clicking the button (not when inputs lose focus)?
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<a class="btn btn-primary btn-lg" role="button" >Add</a>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
<script type="text/javascript">
function AppViewModel() {
this.firstName = ko.observable();
this.lastName = ko.observable();
}
ko.applyBindings(new AppViewModel());
</script>
Upvotes: 0
Views: 549
Reputation: 63699
A few things:
$(document).ready
(or equivalent: $(function() ...
) instead of $(window).load
;script
tag;Here's proof that after those changes it can work:
function AppViewModel() {
alert("b");
this.firstName = "Bert";
this.lastName = "Bertington";
}
$(function() {
ko.applyBindings(new AppViewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
Upvotes: 0
Reputation: 32511
You have mismatched quotes in your script tag. It should be:
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
You can actually drop the type
attribute entirely and just do:
<script src="js/knockout-3.4.0.js"></script>
and it'll still work fine.
Upvotes: 2