Pages

Monday, January 28, 2013

Knock-out simple code



// Here's my data model

///
///

var ViewModel = function (first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.computed(function () {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
        return this.firstName() + " " + this.lastName();
    }, this);
};

var ViewMode2 = function (first, last) {
    var self = this;
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.computed(function () {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
        if (self.firstName().length == 0 || self.lastName().length == 0) return 'missing data';
        return self.firstName() + " " + self.lastName();
    }, this);
};


$(function () {
   // ko.applyBindings(new ViewModel("Refky", "Wahib")); // This makes Knockout get to work   
    ko.applyBindings(new ViewMode2("Refky", "Wahib")); // This makes Knockout get to work   
});

 -------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script type="text/javascript" src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
      
        <script type="text/javascript" src="js/main.js"></script>

        <link rel="stylesheet" type="text/css" href="css/main.css" />
        <title>sample 1</title>
   
    </head>
<body>
<div class='liveExample'>
    <p>First name:
        <input data-bind='value: firstName' />
    </p>
    <p>Last name:
        <input data-bind='value: lastName' />
    </p>
     <h2>Hello <span data-bind='text: fullName'> </span></h2>
</div>
<div data-bind='text: firstName' class='demo'></div>
<input type='submit'></input>
</body>
</html>

 ---------------------------

body {

    font-family: arial;

    font-size: 14px;

}

.liveExample {

    padding: 1em;

    background-color: #EEEEDD;

    border: 1px solid #CCC;

    max-width: 655px;

}

.liveExample input {

    font-family: Arial;

}

.liveExample b {

    font-weight: bold;

}

.liveExample p {

    margin-top: 0.9em;

    margin-bottom: 0.9em;

}

.liveExample select[multiple] {

    width: 100%;

    height: 8em;

}

.liveExample h2 {

    margin-top: 0.4em;

    font-weight: bold;

    font-size: 1.2em;

}

.demo, input[type=submit] {

    background-color:lightgreen;

    padding:5px;

    margin-top:2px;

}