且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该在淘汰赛中使用括号

更新时间:2023-02-16 22:41:06

在使用 observable 或执行任何其他方法时,您可以在淘汰赛中使用 ().Knockout observables 是函数,被调用以返回您要查找的内容或允许您分配新值.

在淘汰赛中,您使用 object.property() 检索值并使用 object.property(newValue) 为该属性分配值.

在淘汰赛网站中查看文档,特别是关于observables,展示了查询和编写 observables 时 () 的使用.

引用:

var myViewModel = {人名:ko.observable('Bob'),人物年龄:ko.observable(123)};

  • 要读取 observable 的当前值,只需调用不带参数的 observable.在这个例子中, myViewModel.personName() 将返回 '​​Bob',而 myViewModel.personAge() 将返回 123.

  • 要将新值写入可观察对象,请调用可观察对象并将新值作为参数传递.例如,调用myViewModel.personName('Mary') 会将名称值更改为 'Mary'.

  • 要将值写入模型对象的多个可观察属性,您可以使用链接语法.例如,myViewModel.personName('Mary').personAge(50) 将更改名称值为Mary",年龄值为 50.

Knockout 的交互式教程也非常不错,值得一读.

I am a beginner in Knockout and I must say I often get confused regarding when to use (). Is there any general tip/trick regarding when would you use () against when you would not because at the moment I am just doing trial and error. If the binding throws error or doesn't update values I remove () else I put.

You use () in knockout when using observables or when executing any other method. Knockout observables are functions, invoked to return you what you looking for or allow you to assign new values.

In knockout you use object.property() to retrieve a value and object.property(newValue) to assign a value to that property.

On the knockout website checkout the documentation, specifically the section on observables, which shows you the use of the () when querying and writing observables.

To quote:

var myViewModel = {
    personName: ko.observable('Bob'),
    personAge: ko.observable(123)
};

  • To read the observable’s current value, just call the observable with no parameters. In this example, myViewModel.personName() will return 'Bob', and myViewModel.personAge() will return 123.

  • To write a new value to the observable, call the observable and pass the new value as a parameter. For example, calling myViewModel.personName('Mary') will change the name value to 'Mary'.

  • To write values to multiple observable properties on a model object, you can use chaining syntax. For example, myViewModel.personName('Mary').personAge(50) will change the name value to 'Mary' and the age value to 50.

Knockout's interactive tutorial is also quite nice and well worth going through.