文章出處

返回目錄

在面向對象的程序設計里,對象是核心,一切皆為對象,對象與對象之間的關系可以表現為繼承和組合,而在Knockoutjs或者JS里,也存在著對象的概念,今天主要說一下JS里的對象及對象的組合。

JS里對象可以使用{}生成,也可以使用function(){}方式生成,而使用function(){}方式我認為更靈活,使用{}方式更正規,我這里總結了一下,也是我的習慣,如果對象只是getter,setter的屬性塊,

可以使用{}的方式,如果對象比較復雜,由屬性,方法 組成,這時最好使用function(){}的方式,下面舉例說明。

下面定義一個user對象,使用{}方式

var User={
   Name:"zzl",
   Gander:"male"
}

下面是一個User對象的function(){}的形式

var User=function(){
this.Name="zzl";
this.Gander="male";
}
//為了調用上的方便,層次的清晰,我們在調用根元素時,最好把this重新定義,看下面代碼:
var User=function(){
  var self=this;//這里的self表示User對像
  self.Name="zzl";
  self.Gander="male";
  self.Remove=function(){
  console.log(this.Name);//這里的this表示當前你觸發的記錄(user可以有多個)
 }
}

好了,有了對象的概念之后,我們來看一下Knockoutjs里如何使用對象,事實上,在Knockoutjs里的viewmodel,即我們的頁面數據綁定源,就是一個對象,它也完全支持{}和function(){}兩種方式,而我習慣上使用第二次,呵呵,下面我們為view返回一個userList的viewmodel,用來輸出一個user對象的集合,將它綁定到<table>元素上。

JS部分代碼:

  var User = function (id, name) {
        self = this;
        self.id = ko.observable(id);
        self.name = ko.observable(name);
        self.editing = ko.observable(false);
        self.edit = function () {//這里的this是當前調用的對象,而不是UserList,而self才是UserList對象,這也是為什么要使用var self = this語句的原因
            this.editing(true);
        }
    };
    //集合屬性和方法
    var UserList = function () {
        var self = this;
        self.users = ko.observableArray();
        for (var i = 0; i < 10; i++) {
            self.users.push(new User(i, "zzl"));
        }

        // Behavior Remove
        self.removePerson = function () {//data-bind="click:$parent.removePerson"//這句為調用當前對象的父對象上的方法
            self.users.remove(this);
        }
    }

    ko.applyBindings(new UserList());//像view返回一個User集合

看一下HTML代碼:

<div class="liveExample">
    <table>
        <thead>
            <tr>
                <th>編號</th>
                <th>姓名</th>
                <th></th>
            </tr>
        </thead>
        <tbody data-bind="template:{name:'list',foreach: users}">
        </tbody>
    </table>
</div>
<script type="text/html" id="list">
    <tr>
        <td data-bind="text:id"></td>
        <td>
            <input type="text" data-bind="value:name, click:edit" /></td>
        <td>
            <a href="#" data-bind="click:$parent.removePerson">移除</a>
            <span data-bind="visible:editing"><a data-bind='click:save'>保存</a></span>

        </td>
    </tr>
</script>

上面的實例中,實現了對象集合的移除操作,即從users里移除一個User對象,而保存按鈕的顯示是通過你是否單擊文本框決定的,而代碼中的$parent.removePerson意思是說,調用users對象的上一級對象的removePerson方法,如果在C#里,這個結構

會是這樣實現,看代碼:

classUser
{   
public int Id{get;set;}   public string Name{get;set;} } class UserList
{   
public User[] Users{get;set;}   public void RemovePerson(User entity)
{   
this.Users.Remove(entity);   } }

怎么樣,看了我的C#代碼分析,學起JS來也不那么費力了吧,呵呵。

 

 返回目錄


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()