0

我有一个 foreach 模板在页面上显示作业列表。在每项工作中,我都有一份工作说明清单。我在设置适当的 observable 以允许在视图中更新工作说明时遇到问题。

这是 jsFiddle 的链接:http: //jsfiddle.net/b3B8p/

或者,这里是它的代码。我不确定是将子列表的可观察数组放入 Job 对象本身还是放入 View ...

<div data-bind="foreach: jobs">
    <div>
        <div class="jobContainer">
            <label data-bind="text: JobTitle"></label> 
            <label data-bind="text: CompanyName"></label>
            <div class="jobDetails" data-bind="visible: expanded">
                <label data-bind="text: City"></label>
                <label data-bind="text: State"></label>
                <div data-bind="foreach: Notes">
                    <label data-bind="text: Text"></label>               
                </div> 
            </div>                           
        <div>
        <a href="#" data-bind="click: $parent.toggle, text: linkLabel">Expand</a> 
        <a href="#" data-bind="click: $parent.addNote">Add Note</a>  
    </div>    
</div>    


function JobNote() {
    this.Text = "some text!";       
}

function Job() {
    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");
    this.Notes = ko.observableArray([
       new JobNote(),
       new JobNote(),       
    ]);

    this.someValue = ko.observable().extend({ defaultIfNull: "some default" });

    this.expanded = ko.observable(false);

    this.linkLabel = ko.computed(function () {
        return this.expanded() ? "collapse" : "expand";
    }, this);      
};

var viewModel = function () {
    this.jobs= ko.observableArray([
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),        
        new Job(),
    ]);

    this.toggle = function (item) {
        item.expanded(!item.expanded());
    }

    this.addNote = function(job) {
         // what should go in here?
    }    
};

ko.applyBindings(new viewModel());​
4

1 回答 1

1

正如 Niko 在这种情况下所说,我会将方法添加到类中。像这样。

function Job() {
    var self = this;

    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");

    this.Notes = ko.observableArray([
       new JobNote(),
       new JobNote(),       
    ]);

    this.someValue = ko.observable().extend({ defaultIfNull: "some default" });

    this.expanded = ko.observable(false);

    this.linkLabel = ko.computed(function () {
        return this.expanded() ? "collapse" : "expand";
    }, this);   

    this.toggle = function () {
        self.expanded(!self.expanded());
    };

    this.addNote = function () {
        self.Notes.push(new JobNote());
    }    
};

这使一切都保持良好和封装。

希望这可以帮助。

于 2012-05-15T15:41:31.177 回答