[Knockout] 學習手記(一) 基本定義

[Knockout] 學習手記(一) 基本定義


    <title></title>
    <script src="Scripts/knockout-2.2.0.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span data-bind="text:firstName"></span>
        <input data-bind="value:lastName" />
        <input data-bind="value:fullName" />
        <a href="#" data-bind="click:click">轉大寫</a>
    </form>
</body>
</html>
<script type="text/javascript">
    function AppViewModel() {
        //可觀物件 ko.observable(" ") 
        this.firstName = ko.observable("Json");
        this.lastName = ko.observable("Bob");

        //合拼或合計 ko.computed
        this.fullName = ko.computed(function () {
            return this.firstName() + " " + this.lastName();
        }, this);

        //定義事件方式   
        this.click = function () {
            var s = this.lastName();
            this.lastName(s.toUpperCase()); //轉大寫
        }
    }
    ko.applyBindings(new AppViewModel()); //啓動 Ko
</script>