Knockout學習筆記之一

1.  四大關鍵理念:javascript

  A. DeclarativeBindings(聲明式綁定)html

  Easily associate DOM elements with model data using a concise, readable syntaxjava

  使用簡單易讀的語法方便地將模型數據與DOM元素綁定在一塊兒api

  B. AutomaticUIRefresh(頁面自動刷新)app

  When your data model's state changes, your UI updates automaticallyide

  C. DependencyTracking(依賴追蹤)函數

  Implicitly set up chains of relationships between model data, to transform and combine itui

  使用可觀察對象在模型數據之間設立隱性關係鏈,用於數據轉換和綁定。this

  D. Templating(模板)spa

  Quickly generate sophisticated, nested UIs as a function of your model data

  內置模板引擎、爲你的模型數據快速編寫複雜的 UI 展示

2. 聲明式綁定

  聲明式綁定即它的聲明的同時也進行了綁定(本身的理解)。

3. applyBindings 

  Activates knockout.js -ko.applyBindings(new AppViewModel());

  激活knockout.js(即激活data-bind屬性) 

4. observables - these are properties that automatically will issue notifications whenever their(View Models)  value changes

  雙向綁定,當ViewModel中的值發生變化時,Dom元素的值也會相應地發生變化,反之亦然。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title></title>
    <script type="text/javascript" src="knockout-3.4.0.js"></script>
       <script type="text/javascript">
        window.onload = function ()
        {
             ko.applyBindings(new AppViewModel());
        }
    
    function AppViewModel()
    {
        this.firstName = ko.observable("Hello ");
        this.lastName = ko.observable("World!");
        this.fullName = ko.computed(function () {
            return this.firstName() + " " + this.lastName();
        },this);
        this.capitalizeLastName = function ()
        {
            var currentVal = this.lastName();
            this.lastName(currentVal.toUpperCase());
        }
    }
    
    </script>
</head>
<body>
   <P>First Name:<input data-bind="value: firstName" /></P>
   <P>Last Name:<input data-bind="value: lastName" /></P>
   <p>FullName:<input data-bind="value: fullName" /></p>
   <button data-bind="click: capitalizeLastName">Go Caps</button>
</body>
</html>
View Code

5. knockout例子(座位預訂)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title></title>
    <script type="text/javascript" src="knockout-3.4.0.js"></script>
    <script type="text/javascript">
        function SeatReservation(name,initialMeal)
        {
            var self = this;
            self.name = name;
            self.meal = ko.observable(initialMeal);
            self.formattedPrice = ko.computed(function () {
                var price = self.meal().price;
                return price ? "$" + price.toFixed(2) : "None";
            });
        }

        function ReservationsViewModel()
        {
            var self = this;
            self.availableMeals = [
                { mealName: "Standard(Sandwich)", price: 0 },
                { mealName: "Premium:(lobster)", price: 34.95 },
                { mealName:"Ultimate(whole zebra)",price:290}
            ];
            self.seats = ko.observableArray([
                new SeatReservation("Steve", self.availableMeals[0]),
                new SeatReservation("Bert", self.availableMeals[0])
            ]);

            self.addSeat = function () {
                self.seats.push(new SeatReservation("", self.availableMeals[0]));
            };

            self.removeSeat = (function (seat) {
                self.seats.remove(seat);
            });

            self.totalSurcharge = ko.computed(function () {
                var total = 0;
                for (var i = 0; i < self.seats().length; i++)
                {
                    total += self.seats()[i].meal().price;
                }
                return total;
            })
        }
        window.onload = function () {
            ko.applyBindings(new ReservationsViewModel());
        }


    </script>
</head>
<body>
    <h2>Your seat reservations</h2>
    <table>
        <thead>
            <tr>
                <th>Passenger name</th>
                <th>Meal</th>
                <th>Surcharge</th>
            </tr>
        </thead>
        <tbody data-bind="foreach:seats">
            <tr>
            <td><input data-bind="value:name"/></td>
            <td><select data-bind="options:$root.availableMeals,value:meal,optionsText:'mealName'"></select></td>
            <td data-bind="text:formattedPrice"></td>
            <td><a href="#" data-bind="click:$root.removeSeat">Remove</a></td>
            </tr>
        </tbody>
    </table>
    <h3 data-bind="visible:totalSurcharge()>0">
        Total surcharge:$<span data-bind="text:totalSurcharge().toFixed(2)"></span>
    </h3>
    <button data-bind="click:addSeat,enable:seats().length<10">Reserve another seat</button>

</body>
</html>
View Code

6.Knockout使用<!--ko--><!--/ko-->來表示循環的開始和結束;

   切記不是註釋!

7. 總結分析:

    問題一:在第一個例子中,在調用ko.computed()方法時,第二個參數this的做用?

    答:這個和JS中的基本一致,是爲了ko.computed()方法內部的使用而傳入的;

    問題二:在第二個例子中,何時用meal,何時用meal()?(如下爲官網說法)

  Notice that, because the meal property is an observable, it's important to invoke meal() as a function (to obtain
  its current value) before attempting to read sub-properties. In other words, write meal().price, not meal.price.

    由於meal的屬性是observable,在獲取該類型當前值時,必須將其做爲一個函數來使用,即 meal() ,換句話說就是meal().price,而不是meal.price。

相關文章
相關標籤/搜索