Basic Knockout.js using with external .js file.

1,745 views
Skip to first unread message

kristij...@gmail.com

unread,
May 14, 2013, 8:00:48 PM5/14/13
to knock...@googlegroups.com
Hi all,
I'm very new to JavaScript, knockout.js etc. I like to go straight to the point:
I want to learn how to use knockout.js with external .js file.
I'm looking forward for your respond.
Here's a basic example I want to make it work:
(Note: When I put the javascript.js code to <script>...</script> inside the HTML file, it works like a charm.)

HTML:
...
<script type="text/javascript" src="knockout-2.2.1.js"></script>
<script type="text/javascript" src="javascript.js"></script>
...
<h1>Introduction</h1>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Second name: <input data-bind="value: lastName" /></p>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeLastName">Go caps!</button> 
...

JAVASCRIPT.JS:
ko.applyBindings(new IntroductionViemModel);

function IntroductionViemModel()
{
this.firstName = ko.observable("Name");
this.lastName = ko.observable("Surname");
this.fullName = ko.computed(function() {return this.firstName() + " " + this.lastName()}, this);
this.capitalizeLastName = function(){var currentVal = this.lastName(); this.lastName(currentVal.toUpperCase());}
 
 

Patrick Steele

unread,
May 14, 2013, 11:16:42 PM5/14/13
to knock...@googlegroups.com
Put the call to ko.applyBindings in the document ready handler.  If you're using jQuery, this should work:

$(function() {
    ko.applyBindings(new IntroductionViemModel);
});

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Kristijan Rusu

unread,
May 15, 2013, 6:19:04 AM5/15/13
to knock...@googlegroups.com
I'm actually not using JQuery, only knockout.js. How can I do that manually, without using any other library?
I have a task to make a site using only knockout.js and JavaScript file written by myself. 

rpn

unread,
May 15, 2013, 7:40:11 AM5/15/13
to knock...@googlegroups.com
Hi Kristijan-
You would want to put your script tag at the bottom of your page.  That way the DOM elements will be available.

<script type="text/javascript" src="javascript.js"></script>
</body>

Kristijan Rusu

unread,
May 15, 2013, 10:09:23 AM5/15/13
to knock...@googlegroups.com
Thank you were much, this solves the problem I had and explains a lot. Thank you again.
Reply all
Reply to author
Forward
0 new messages