background image

Knockout 与服务器的数据交互 

到目前为止,已经对

MVVM 模式如何帮自己整洁的管理针对动态 UI 的客户端代码,

以及

Knockout 的可监听、绑定、依赖的工作方式有了很好的理解。

在绝大部分的

Web 应用中,你需要从服务器获取数据,再将修改后数据返回。

因为

Knockout 是一个纯客户端库,它能灵活的与各种服务器端技术(ASP.NET,Rails,PHP...)

和任何架构模式,数据库合作。只要服务器端能收发

JSON 格式数据(so easy),我们就可以

使用这种技术。

例子情景
google 的 Tasks 应该很多人都用过吧。我们也来尝试一个。

View Code

<!

DOCTYPE HTML

>

<

html

>

<

head

>

    

<

title

>

Custom Bindings

</

title

>

    

<

script 

src

="../JS/jquery-latest.min.js"

 

type

="text/javascript"></

script

>

    

<

script 

src

="knockout-2.2.0.js"

 

type

="text/javascript"></

script

>

    

<

style 

type

="text/css">

 

   body 

font-family

Helvetica, Arial 

   input:not([type]), 

input[type=text], input[type=password], select 

background-color

#FFFFCC

border

1px solid 

gray

padding

2px

; } 

   .codeRunner ul 

list-style-type

none

margin

1em 0

background-color

#cde

padding

1em

border-radius

0.5em

;  } 

   .codeRunner ul li a 

color

Gray

font-size

90%

text-decoration

none 

   .codeRunner ul li a:hover 

text-decoration

underline 

   .codeRunner 

input:not([type]), input[type=text] 

width

30em

; } 

   .codeRunner input[disabled] 

text-

decoration

line-through

border-color

Silver

background-color

Silver

; } 

   .codeRunner textarea 

width

30em

height

6em

; } 

   .codeRunner form 

margin-top

1em

margin-bottom

1em

; }

    

</

style

>

</

head

>

<

body 

class

="codeRunner">

    

<

h3

>

Goagle Tasks

</

h3

>

    

<

form 

data-bind

="submit:addTask">

        Add task:

<

input 

data-bind

="value:newTaskText" 

placeholder

="What needs to be done?"

 

/>

        

<

button 

type

="submit">

Add

</

button

>

    

</

form

>

    

<

ul 

data-bind

="foreach:tasks,visible:tasks().length > 0 ">

        

<

li

>

            

<

input 

type

="checkbox"

 

data-bind

="checked:isDone"

 

/>