3

问题:我让 Json 从服务器返回。Json 是一系列业务,其中每个业务可以有多个联系人。我还想让联系人成为一个可观察的数组,以便绑定到联系人的 html 元素在删除时得到更新,而数组在编辑时得到更新。

我已经设置了以下 jsFiddle - http://jsfiddle.net/rdotlee/GCwjX/1/

这是我来自 jsFiddle 的视图模型。

    var businessViewModel =
{
    allBusinesses: ko.observableArray([
                                        { name: "Biz1", id: 1, Contacts: [{ name: "Joe", email: "test@test", phone: "555-111-1111" }, { name: "Smith", email: "smith@test", phone: "777-111-2223"}] },
                                        { name: "Biz2", id: 2, Contacts: [{ name: "Joe", email: "test@test", phone: "555-222-1111" }, { name: "Smith", email: "smith@test", phone: "555-111-2222"}] }
                                      ]),

    businessId: ko.observable(1)

};

businessViewModel.selectedBusiness = ko.dependentObservable(function () {
    var biz = this.allBusinesses()[0];

    for (var i = 0; i < this.allBusinesses().length; i++) {
        if (this.allBusinesses()[i].id == this.businessId()) {
            biz = this.allBusinesses()[i];
            break;
        }
    }
    return biz;
}, businessViewModel);

businessViewModel.removeContact = function (contact) {
    ko.utils.arrayRemoveItem(this.selectedBusiness().Contacts, contact);
    ko.applyBindings(businessViewModel, $("#sectionBusinesses")[0]);
} .bind(businessViewModel);

做我需要的最干净/推荐的方法是什么?

谢谢,

4

1 回答 1

1

首先,我不确定您为什么每次删除联系人时都调用 ko.applyBindings 。您通常只想调用一次 applyBindings,而这通常会导致问题。

我建议使用 ko.mapping 插件,这将使整个过程相当轻松。

我还更新了您的 removeContact 以使用更新后的 ViewModel 并稍微更改了您的 selectedBusiness 。

这是小提琴: http: //jsfiddle.net/GCwjX/5/ 和代码:

var jsonData = {
    allBusinesses: [{
        name: "Biz1",
        id: 1,
        Contacts: [{
            name: "Joe",
            email: "test@test",
            phone: "555-111-1111"},
        {
            name: "Smith",
            email: "smith@test",
            phone: "777-111-2223"}]},
    {
        name: "Biz2",
        id: 2,
        Contacts: [{
            name: "Joe",
            email: "test@test",
            phone: "555-222-1111"},
        {
            name: "Smith",
            email: "smith@test",
            phone: "555-111-2222"}]}]
};
var businessViewModel = {
    allBusinesses: ko.observableArray(),
    businessId: ko.observable(1)
};

businessViewModel.selectedBusiness = ko.dependentObservable(function() {
    var biz = this.allBusinesses()[0];
    biz = ko.utils.arrayFirst(this.allBusinesses(), function(item) { 
        return (item.id() === parseInt(this.businessId())); 
    }, this);
    return biz;
}, businessViewModel);

businessViewModel.removeContact = function(contact) {
    this.selectedBusiness().Contacts.remove(contact);
}.bind(businessViewModel);

ko.mapping.fromJS(jsonData, {}, businessViewModel);
ko.applyBindings(businessViewModel);​
于 2012-09-07T12:57:55.350 回答