matt
matt

Reputation: 2997

Getting started on Knockout JS

I am currently developing using ASP.NET, and I'd like to get started on Knockout JS... Basically what I've done is I've copy-pasted the code provided in the first tutorial.

So I put this into my head:

<script type="text/javascript">
    function() {
        // This is a simple *viewmodel* - JavaScript that defines the data and
        behavior of your UI

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

            this.fullName = ko.computed(function() {
            return this.firstName() + " " + this.lastName();    
        }, this);

        this.capitalizeLastName = function() {
            var currentVal = this.lastName();        // Read the current value
            this.lastName(currentVal.toUpperCase()); // Write back a modified value
        };
    }

    // Activates knockout.js
    ko.applyBindings(new AppViewModel());
    }();
</script>

...along with

<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/knockout-2.0.0.js"></script>

In my body I placed

<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<p>
    First name: <strong data-bind="text: firstName"></strong>
</p>
<p>
    Last name: <strong data-bind="text: lastName"></strong>
</p>
<p>
    First name:
    <input data-bind="value: firstName" /></p>
<p>
    Last name:
    <input data-bind="value: lastName" /></p>
<p>
    Full name: <strong data-bind="text: fullName"></strong>
</p>
<button data-bind="click: capitalizeLastName">
    Go caps</button>

The code was all taken from Knockout JS's tutorial, but somehow the values don't bind themselves automatically--in other words it doesn't work for me. Am I missing something here?

Upvotes: 0

Views: 1010

Answers (3)

AlfeG
AlfeG

Reputation: 1473

It's seems to me that You wrongly use anonymous function wrapper.

You need to add more ( ) to code.

(function() { 
 ...
})();

Working example: http://jsfiddle.net/AlfeG/bZatD/

Upvotes: 2

eppdog
eppdog

Reputation: 423

If you didn't want to use jQuery, You could also:

  1. remove your outer self-executing function
  2. put the script referencing knockout view models at the bottom of the body

Upvotes: 1

ColinE
ColinE

Reputation: 70122

It looks to me like you JavaScript code is being executed before the DOM (your HTML) has been rendered. The JavaScript function you have included in the head is executed immediately. You need to ensure that this code is only executed when the page has been fully rendered.

You can do that with the jQuery ready function.

<script type="text/javascript">
  $(document).ready(function () {
    // your existing JavaScript goes here.
  })
</script>

Upvotes: 2

Related Questions