简体   繁体   English

如何使用ko.observableArray?

[英]How to use ko.observableArray?

I have written simple example to learn about how ko.observableArray works. 我编写了一个简单的示例来了解ko.observableArray的工作方式。

**HTML**:
Count is : <span data-bind="text anotherObservableArray().length"> </span>

JS:
var anotherObservableArray = ko.observableArray( [
{ name: "A", type: "A" },
{ name: "B", type: "B" },
{ name: "C", type: "C" }
]);

ko.applyBindings(anotherObservableArray);

Here is the link for the example am trying to implement 这是示例试图实现的链接

http://jsfiddle.net/Rama_Kishore/ZPDBv/ http://jsfiddle.net/Rama_Kishore/ZPDBv/

I was expecting "Count is: 3" output ,instead it's the output is "Count is:" 我原以为“ Count is:3”输出,而不是输出为“ Count is:”

Please let me know why the count is not getting displayed. 请让我知道为什么未显示该计数。

Thanks. 谢谢。

Here is a working fork of your fiddle: 这是您的小提琴的工作叉:

http://jsfiddle.net/myjkk/2/ http://jsfiddle.net/myjkk/2/

Note how the text binding syntax includes a colon: 注意文本绑定语法如何包含冒号:

<span data-bind="text: anotherObservableArray().length"></span>

Note in the javascript how ko.applyBindings is used. 请注意在javascript中如何使用ko.applyBindings See the knockout documentation for Activating Knockout: http://knockoutjs.com/documentation/observables.html 请参阅淘汰赛文档,了解激活淘汰赛: http : //knockoutjs.com/documentation/observables.html

var vm = {
    anotherObservableArray: ko.observableArray([{
        name: "A",
        type: "A"
    }, {
        name: "B",
        type: "B"
    }, {
        name: "C",
        type: "C"
    }])
};

ko.applyBindings(vm);

Also worth noting is that n your original fiddle, you did not include the knockoutjs library. 另外值得注意的是n个原来的小提琴,你没有包括knockoutjs库。

Couple of issues: 几个问题:

  • You didnt include Knockout as a library in js fiddle 您没有在JS小提琴中将Knockout包含为库
  • You didn't provide a vm object that wraps your observable array 您未提供包装可观察数组的vm对象
  • You had a typo in the binding 装订中有错字

Fiddle : link 小提琴: 链接

var vm = {
    anotherObservableArray : ko.observableArray( [
       { name: "A", type: "A" },
       { name: "B", type: "B" },
       { name: "C", type: "C" }
    ])
}
 ko.applyBindings(vm);

ko.observableArray should be a part of model object. ko.observableArray应该是model对象的一部分。
Eg 例如

var viewModel = new function()
{
   this.anotherObservableArray = ko.observableArray(...);
}  

or 要么

var viewModel = {
   anotherObservableArray : ko.observableArray(...);
}  

Apply bindings 应用绑定

ko.applyBindings(viewModel);  

JSFiddle DEMO JSFiddle演示

You can find very good knockout online-tutorial here 您可以在此处在线找到非常好的淘汰赛

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM