简体   繁体   English

Knockout Observable Array Length始终为0

[英]Knockout Observable Array Length always 0

When calling the length of any observable in the customerOverview view model I receive a length of zero. 在customerOverview视图模型中调用任何observable的长度时,我会收到零长度。 There is data present in the observables as the bindings update with data, however the length remains at 0. The base view model, 'CustomerCentral', returns lengths properly. 随着绑定随数据更新,可观察数据中存在数据,但长度保持为0.基本视图模型'CustomerCentral'正确返回长度。 I need the length of some observables in 'CustomerOverview' to do some conditional statements. 我需要'CustomerOverview'中一些observable的长度来做一些条件语句。

HTML Bindings HTML绑定

<ul class="nav nav-list">
      <li class="nav-header">Contacts</li>
      <!--ko  if: customerOverview.contacts().length == 0-->
      <li>No contacts associated with this customer</li>
       <!-- /ko -->
      <!--ko  foreach: customerOverview.contacts()-->
      <li>
      <a data-bind="click: $root.customerOverview.viewContact"><i class="icon-chevron-                        right single pull-right">
       </i><span data-bind="text: FirstName"></span><span data-bind="text: LastName"></span>
      </a></li>
      <!-- /ko -->
</ul>

JS JS

function CustomerOverview() {
        var self = this;        

        self.contacts = ko.observableArray([]);           

        self.getCustomerContacts = function () {
            requestController = "/CRM/CustomerCentral/CustomerContacts";
            queryString = "?id=" + self.customer().Id();
            $.ajax({
                cache: false,
                type: "GET",
                dataType: "json",
                url: baseURL + requestController + queryString,
                headers: { "AuthToken": cookie },
                success:
                        function (data) {
                            if (data.data.length > 0) {

                                self.contacts(ko.mapping.fromJS(data.data));

                                console.log(self.contacts().length);
                            }
                        }
            });
        };
};
   function CustomerCentral() {

        var self = this;

        self.customerOverview = ko.observable(new customerOverview());
};

var vm = new CustomerCentral();
    ko.applyBindings(vm);

Console cmd: vm.customerOverview().contacts().length 0 Console cmd:vm.customerOverview()。contacts()。length 0

---------------------------SOLUTION ---------------------- observableArray.push() ---------------------------解决方案---------------------- observableArray.push()

The issue turned out to be this line : 问题结果是这一行:

  self.contacts(ko.mapping.fromJS(data.data));

SOLUTION: Adding .push() to this enabled the length property of the array to be incremented. 解决方案:在此处添加.push()可以使数组的length属性递增。 I had assumed ko.mapping would handle this but it does not. 我曾假设ko.mapping会处理这个问题,但事实并非如此。 Changing the variable to observable had no effect. 将变量更改为observable无效。

 $.each(data.data, function () {
          self.contacts.push(ko.mapping.fromJS(this));
           console.log(self.contacts().length);
                                    });

I think your problem is not having your customerOverview property as observable 我认为您的问题是没有将您的customerOverview属性视为可观察的

try: 尝试:

 self.customerOverview = ko.observable(new CustomerOverview());

or 要么

 self.customerOverview = ko.computed(function(){
       return new CustomerOverview();
 });

Working sample: 工作样本:

http://jsfiddle.net/dvdrom000/RHhmY/1/ http://jsfiddle.net/dvdrom000/RHhmY/1/

html HTML

<span data-bind="text: customerOverview().contacts().length"></span>
<button data-bind="click: customerOverview().getCustomerContacts">Get contacts</button>

js JS

function CustomerOverview() {
        var self = this;        

        self.contacts = ko.observableArray([]);           

        self.getCustomerContacts = function () {
            self.contacts.push(1);
            self.contacts.push(2);
            self.contacts.push(3);            
        };
};
   function CustomerCentral() {

        var self = this;
        // Is this a correct way. Am I breaking something with this?
        self.customerOverview = ko.observable(new CustomerOverview());
};

var vm = new CustomerCentral();
    ko.applyBindings(vm);

observableArray.push() observableArray.push()

The issue turned out to be this line : 问题结果是这一行:

self.contacts(ko.mapping.fromJS(data.data));

SOLUTION: Adding .push() to this enabled the length property of the array to be incremented. 解决方案:在此处添加.push()可以使数组的length属性递增。 I had assumed ko.mapping would handle this but it does not. 我曾假设ko.mapping会处理这个问题,但事实并非如此。 Changing the variable to observable had no effect. 将变量更改为observable无效。

$.each(data.data, function () {
          self.contacts.push(ko.mapping.fromJS(this));
           console.log(self.contacts().length);
                                    });

Knockout provides a set of manipulation functions for arrays that mirror the functions found in in JavaScript; Knockout为数组提供了一组操作函数,用于镜像JavaScript中的函数; pop, push, shift, unshift, reverse, sort, and splice. pop,push,shift,unshift,reverse,sort和splice。 Along with performing the operations you'd expect, these array functions will also automatically notify any observers that the array has changed. 除了执行您期望的操作外,这些数组函数还将自动通知任何观察者数组已更改。 The JavaScript methods wont. JavaScript方法不会。 If you want your UI to update when the array counts change, you'll want to be careful to use the Knockout functions. 如果您希望在数组计数发生变化时更新UI,您需要小心使用Knockout函数。

Reference: http://ryanrahlf.com/knockout-js-observablearray-not-updating-the-ui-heres-how-to-fix-it/ 参考: http//ryanrahlf.com/knockout-js-observablearray-not-updating-the-ui-heres-how-to-fix-it/

So basically, to solve your problem, you just need to use the knockout push function directly on the observable array instead of using the javascript push method. 基本上,要解决您的问题,您只需要在可观察数组上直接使用knockout push函数,而不是使用javascript push方法。 Hence: 因此:

Change this: 改变这个:

self.contacts( ).push( data.data );

By this: 这样:

self.contacts.push( data.data );

And you will be able to use the contacts( ).length property on your html and be notified on every change in the array. 并且您将能够在html上使用contacts()。length属性,并在数组中的每个更改时得到通知。

I had problems like this, and IIRC, it was because I was using double equals (==) instead of triple equals (===) in the comment conditionals. 我有这样的问题和IIRC,这是因为我在评论条件中使用了双等号(==)而不是三等号(===)。 Give it a shot. 试一试。

Instead of: 代替:

self.contacts(ko.mapping.fromJS(data.data));

You should have: 你应该有:

self.contacts(ko.mapping.fromJS(data.data)**()**);

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

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