gpt4 book ai didi

javascript - Knockout Observable 数组长度始终为 0

转载 作者:太空狗 更新时间:2023-10-29 13:26:47 24 4
gpt4 key购买 nike

在 customerOverview View 模型中调用任何可观察对象的长度时,我收到的长度为零。当绑定(bind)随数据更新时,可观察对象中存在数据,但长度保持为 0。基本 View 模型“CustomerCentral”正确返回长度。我需要“CustomerOverview”中一些可观察对象的长度来执行一些条件语句。

HTML 绑定(bind)

<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

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);

控制台命令:vm.customerOverview().contacts().length0

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

问题原来是这一行:

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

解决方案:将 .push() 添加到此可以使数组的 length 属性增加。我原以为 ko.mapping 会处理这个问题,但事实并非如此。将变量更改为 observable 没有任何效果。

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

最佳答案

我认为你的问题是你的 customerOverview 属性没有被观察到

尝试:

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

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

工作样本:

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

html

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

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);

关于javascript - Knockout Observable 数组长度始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15555704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com