Knockout在运行时添加子对象

时间:2013-03-14 08:55:02

标签: knockout.js parent-child

我对knockoutjs很新,需要一些像viewmodel问题这样的亲子帮助。

var DailyItems = function (data) {
var p = this;
this.Day = ko.observable(data.Day);
this.Date = ko.observable(data.Date);
this.Required = ko.observable(data.Required);
this.RequiredActive = ko.observable(true);
this.SetupTime = ko.observable(data.SetupTime);
this.CloseTime = ko.observable(data.CloseTime);
this.MinHrsPerDay = ko.observable(data.MinHrsPerDay);
this.MaxHrsPerDay = ko.observable(data.MaxHrsPerDay);
this.MinWorkShift = ko.observable(data.MinWorkShift);
this.WorkSegments = ko.observableArray([]);
var records = $.map(data.WorkSegments, function (x) { return new WorkShift(p, x) });
this.WorkSegments(records);
this.EnableAdd = ko.observable(ko.toJS(this.WorkSegments).length < 8);
this.Add = function () {
    this.WorkSegments.push({
        Parent: p,
        ID: "",
        Day: data.Date,
        Location: UNIT_ID,
        Role: "",
        EmployeeRoles2: "[]",
        ShiftStart: "",
        ShiftEnd: "",
        LocationActive: true,
        RoleActive: true
    });
    this.EnableAdd(ko.toJS(this.WorkSegments).length < 8);
}
this.Delete = function (item) {
    this.WorkSegments.remove(item);
    this.EnableAdd(ko.toJS(this.WorkSegments).length < 8);
}

};

子模型如下:

var WorkShift = function (parent, data) {
var self = this;
this.Parent = ko.observable(parent);
this.ID = ko.observable(data.ID);
this.Day = ko.observable(data.Day);
this.Location = ko.observable(data.Location);
this.Parent = ko.observable(0);
this.LocationActive = ko.observable(true);
this.RoleActive = ko.observable(true);
this.ShiftStart = ko.observable(data.ShiftStart);
this.ShiftEnd = ko.observable(data.ShiftEnd);
this.EmployeeRoles2 = ko.observableArray([{ "ID": 0, "Name": "Volume"}]);
this.Location.subscribe(function (branchId) {
    $.ajax({
        type: "POST",
        url: SERVER_PATH + '/WebServices/AttributeService.asmx/GetDataOnLocationChange',
        data: "{" + "clientId: '" + CLIENT_ID
                    + "', unitId: '" + branchId
                    + "', effectiveDate:'" + EFFECTIVE_DATE
                    + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (res) {
            var d = JSON.parse(res.d);
            self.EmployeeRoles2(d.Roles);
            if (d.IsSection == true) {
                self.RoleActive(false);
                self.Parent(d.Parent);
            }
            else if (d.IsRegularBranch == false) {
                self.RoleActive(false);
                self.LocationActive(false);
            }
            else {
                self.RoleActive(true);
                self.LocationActive(true);
            }
            var tasks = self.Parent().WorkSegments();
            //Requirement: for any day of the week, if there is more than one work segment
            //at different branches the required type should be set to 'On' and made disable
            if (tasks.length > 1) {
                ko.utils.arrayForEach(tasks, function (i) {
                    if ((d.isSection == false && i.Location() != self.Location()) || (d.isSection == true && self.Parent() != i.Parent())) {
                        self.Parent().Required('O');
                        self.Parent().RequiredActive(false);
                        return;
                    }
                    else {
                        self.Parent().Required('E');
                        self.Parent().RequiredActive(true);
                    }
                });
            }
        },
        error: HandleLocationChangeError
    });
} .bind(this));
this.Role = ko.observable(data.Role);
this.TimeRangeTotal = ko.dependentObservable(function () {
    var timeRangetotal = 'T: 0';
    var startTime = parseInt(ko.toJS(this.ShiftStart));
    var endTime = parseInt(ko.toJS(this.ShiftEnd));
    if (!isNaN(startTime)) {
        var duration = endTime - startTime;
        var hrs = parseInt(duration / 100);
        var mins = duration % 100;
        if (mins == 55 || mins == 70 || mins == 85)
            mins = mins - 40; //addresses deducting from a total hour (e.g. 1400 - 845)
        timeRangetotal = "T: " + hrs + ":" + mins;
    }
    return timeRangetotal;
}, this);

}

请注意,Child对象是Dependent observable和subscribe方法。我想在运行时添加一个子对象,因此在DailyItems模型中添加Add()函数。我的问题是如何在Add()方法中提供subscribe方法和可靠的observable?

感谢有人可以提供帮助。

此致 Chathu

2 个答案:

答案 0 :(得分:0)

道歉,我没有时间得到完整答案,但您应该查看mapping plugin以将您的JS数据转换为视图模型。

在你的add方法中,你需要创建一个子视图模型,而不仅仅是将一个普通的JS对象添加到WorkSegments数组中:

this.Add = function(){     var data = {         家长:p,         ID: ””,         日:data.Date,         位置:UNIT_ID,         角色:“”,         EmployeeRoles2:“[]”,         ShiftStart:“”,         ShiftEnd:“”,         LocationActive:是的,         RoleActive:true     };     var child = new WorkShift(p,data);     。this.WorkSegments()推(子);

另外,您可以更改此代码:

this.EnableAdd = ko.observable(ko.toJS(this.WorkSegments).length < 8);

为:

this.EnableAdd = ko.computed(function() { this.WorkSegments().length < 8; });

答案 1 :(得分:0)

以下是工作代码版本。它现在就像一个美女:)

this.Add = function () {
    var data = {
        Parent: p,
        ID: "",
        Day: this.Date,
        Location: UNIT_ID,
        ParentBranch:0,
        Role: "",
        EmployeeRoles2: "[]",
        ShiftStart: "",
        ShiftEnd: "",
        LocationActive: true,
        RoleActive: true
    };
    var child = new WorkShift(p, data);
    this.WorkSegments.push(child);