Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KO 的计算属性 computed 上篇 #105

Open
ahua52 opened this issue Aug 14, 2016 · 0 comments
Open

KO 的计算属性 computed 上篇 #105

ahua52 opened this issue Aug 14, 2016 · 0 comments

Comments

@ahua52
Copy link

ahua52 commented Aug 14, 2016

初始KO,计算属性(computed)尚未用到,在此做一个学习笔记

Computed observable是如何工作的

如果你已经有了一个监控属性firstName和lastName,如果你想显示全名该怎么做呢?这个时候你就可以通过计算属性来实现,这个方法依赖于一个或多个监控属性,如果任何依赖对象发生改变他们就会跟着改变.

创建一个简单的viewmodel

function MyViewModel(){
       this.firstName=ko.observable('Bob');
       this.lastName=ko.observable('Smith');
}

firstName和lastName 具备observable属性,现在可添加一个computed属性返回全名

function MyViewModel(){
       this.firstName=ko.observable('Bob');
       this.lastName=ko.observable('Smith');
       this.fullName=ko.computed(function(){
             return this.firstName()+" "+this.lastName();
        },this);
}

下面你就可以绑定fullName 到你的dom上

<span data-bind="text: fullName"></span>

当firstName或者lastName变化,它将会随时更新(当依赖关系发生变化,你的计算函数就会被调用,并且它的值都会更新到UI对象或其他的依赖属性上去)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant