天天看點

執行個體講解:Observable執行個體講解:Observable

基礎概念二:Observable與computed

縱觀KO的所有應用場景,基本上這2個屬性至少會用到一個。個人認為這是KO最常使用的東西。他們用法如下:

  • Observable(監控屬性):監控自身屬性的變化,向外部發送通知。外部通過subscribe方法來訂閱屬性的變化事件。
  • Computed(依賴屬性):在早期版本中叫做dependentObservable,它通常依賴于其他的Observable,通過計算得出自己的資料。當依賴項改變的時候,computed屬性會接到通知,然後同步更新自身

執行個體講解:Observable

基本文法

1、定義

var myViewModel = {
    personName: ko.observable('Bob'),//定義叫做personName的監控屬性
    personAge: ko.observable(123)//定義叫做personAge的監控屬性
};      
4、訂閱屬性修改事件

   
           
myViewModel.personName.subscribe(function(newValue) {
    alert("The person's new name is " + newValue);
});

      

html源碼:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../Scripts/knockout-3.0.0.js"></script>
    <script src="../Scripts/jquery-1.5.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var listMode = function () {
                self = this;
                self.firstName = ko.observable("5");
                self.lastName = ko.observable("cihai");
                self.fullName = ko.computed(function () {
                    return self.firstName() + self.lastName();
                }, this);
                self.firstName.subscribe(function (newValue) {
                    alert(newValue);

                });
            }

            ko.applyBindings(new listMode());
        });
    </script>
</head>
<body>

   <strong>firstName</strong><input data-bind="value: firstName" /><br />
       <strong>lastName</strong><input data-bind="value: lastName" /><br />
    <strong>fullName</strong><input data-bind="value: fullName" /><br />
          直接顯示<br />
    <button type="button" οnclick="show();">顯示</button>
</body>
</html>
           

繼續閱讀