如何在按下按钮时添加新行

How to add a new row on button press?

本文关键字:添加 新行 按钮      更新时间:2023-09-26

这是我的按钮

<button class="btn btn-primary" type="button" data-bind="click: $parent.addSlot" value="Add">Add Timing</button>

实际上,当这个按钮被按下时,我想要插入另一行。所以我按照

var Schedule = (function () {
    function Schedule(data) {
        this.id = ko.observable('' + Schedule._id++);
        this.day = ko.observable('');
        this.fromtime = ko.observable('');
        this.totime = ko.observable('');
        this.hospital = ko.observable('');
        this.hospitalId = ko.observable('');
        if (data != null) {
            this.id = ko.observable('' + Schedule._id++);
            this.day = ko.observable(data['day']);
            this.fromtime = ko.observable(data['fromtime']);
            this.totime = ko.observable(data['totime']);
            this.hospital = ko.observable(data['hospital']);
            this.hospitalId = ko.observable(data['hospitalId']);
        }
    }
    Schedule._id = 0;
    return Schedule;
})();
function vm() { 
var self = this; 
self.addSlot = function () { 
    //self.schedules.push(new Model.Schedule(null));
    console.log('added');
    self.doctor.schedules.push(new Schedule(null));
    };
self.removeSlot = function () { 
console.log('removed'); 
//self.schedules.remove(this);
self.doctor.schedules.remove(this);
} 
}; 
var viewModel = new vm(); 
ko.applyBindings(viewModel);

这是我的完整代码

var Doctor = (function () {
    function Doctor(data) {
        this.id = ko.observable('');
        this.name = ko.observable('');
        this.degree = ko.observable('');
        this.gender = ko.observable('');
        this.username = ko.observable('');
        this.password = ko.observable('');
        this.email = ko.observable('');
        this.mobile = ko.observable('');
        this.imgFile = ko.observable('');
        this.imgSrc = ko.observable('');
        this.imagePath = ko.observable('');
        this.userid = ko.observable('');
        this.department = ko.observable('');
        this.schedules = ko.observableArray([]);
        if (data != null) {
            this.id = ko.observable(data['id']);
            this.name = ko.observable(data['name']);
            this.degree = ko.observable(data['degree']);
            this.gender = ko.observable(data['gender']);
            this.username = ko.observable(data['username']);
            this.password = ko.observable(data['password']);
            this.email = ko.observable(data['email']);
            this.mobile = ko.observable(data['mobile']);
            this.imgFile = ko.observable(data['imgFile']);
            this.imgSrc = ko.observable(data['imgSrc']);
            this.imagePath = ko.observable(data['imagePath']);
            this.userid = ko.observable(data['userid']);
            this.department = ko.observable(data['department']);
        }
    }
    return Doctor;
})();

var Schedule = (function () {
    function Schedule(data) {
        this.id = ko.observable('' + Schedule._id++);
        this.day = ko.observable('');
        this.fromtime = ko.observable('');
        this.totime = ko.observable('');
        this.hospital = ko.observable('');
        this.hospitalId = ko.observable('');
        if (data != null) {
            this.id = ko.observable('' + Schedule._id++);
            this.day = ko.observable(data['day']);
            this.fromtime = ko.observable(data['fromtime']);
            this.totime = ko.observable(data['totime']);
            this.hospital = ko.observable(data['hospital']);
            this.hospitalId = ko.observable(data['hospitalId']);
        }
    }
    Schedule._id = 0;
    return Schedule;
})();
//here goes the global variables 
var doctor = null; 
var schedules = []; //////////////////////////////
var hospitals = [];//////////////////////////////
//ajax call 
$.ajax({ 
    type: "GET", 
    url: projectUrl + "getDoctors", 
    dataType: "json", 
    jsonp: true, 
    async: false, 
   success: function (data) { 
      //alert(data); 
      $.each(data.doctors, function (index, currPat) { 
         if (currPat.userid == "${IDis}") { 
            //set value to doctor 
            doctor = currPat; 
            console.log(doctor);
            $.each(currPat.schedules, function (index1, schedule) { 
               //push each schedules to gloabl schedules array 
               //schedules.push(new Model.Schedule(schedule));
               //schedules.push(new Model.Schedule(schedule));
               //hospitals.push(schedule.hospital);
               schedules.push(new Schedule(schedule)); 
               hospitals.push(schedule.hospital); 
           }); 
       } 
    }); 
} 
}); 

var doc = new Doctor(doctor); 
doc.schedules(schedules);
doc.imgFile = 'imagefileValue'; 
doc.imagePath = 'imagePathValue'; 
//var sche = new Model.Schedule(doctor.schedules[0]); 
function vm() { 
    var self = this; 
    self.genderOptions = ['Male', 'Female']; 
    self.hospitalOptions = hospitals; 
    self.weekdays = ["Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday","Sunday"];
self.degreeOptions = ['BDS', 'DA(Anaesthesia)', 'MBBS', 'MBBS,MD', 'MBBS,MD(Med)PMCH', 'MBBS,MD,FNB', 'MBBS,MS(ENT)', 'MD,DM,FISC', 'MD,MS,PhD,DSc', 'MDS(Oral Surgery)', 'MS(OPHTH),FICS', 'MS,DNB,MRCS(Edin),MCh(GASTRO)'] 
self.departmentOptions = ['Anesthesiology', 'Bio-Chemistry', 'Cardiac Rehab Yoga', 'Cardio Thoracic Surgery', 'Cardiology', 'Chest Physician', 'Cosmetic Plastic and Hand Surgery', 'Critical Care', 'Dental&Facio maxillary Surgery', 'Dermatology', 'Diabetology', 'Dietary Services', 'Emergency Medicine', 'Endocrinology', 'Endoscopic,Head & Neck Surgery', 'Endoscopy', 'Gastroenterology', 'Gastrointestinal Medicine', 'General Medicine', 'General Surgery', 'Geriatrics', 'Gynecology', 'Hematology', 'Internal Medicine', 'Interventional Radiology', 'Laboratory Medicine', 'Laparoscopic Surgery', 'Medical Oncology', 'Micro-Biology', 'Nephrology', 'Neuro-Surgery', 'Neurology', 'Nuclear Medicine', 'Nuclear Medicinee', 'Obstetrics and Gynecology', 'Ophthalmology', 'Orthopedics & Traumatology', 'Otorhinolaryngology', 'Pathology', 'Pediatric Cardiology', 'Pediatric Surgery', 'Pediatrics', 'Physician', 'Physiotherapy', 'Psychiatry', 'Pulmonology', 'Radio-Diagnosis', 'Radiology', 'Rheumatology', 'Surgical Gastro-Enterology', 'Surgical Oncology', 'Urology', 'Vascular Surgery'] 
    self.doctor = doc; 
//self.schedule = sche; 
//self.schedules = ko.observableArray(schedules); 
self.addSlot = function () { 
    //self.schedules.push(new Model.Schedule(null));
    console.log('added');
    self.doctor.schedules.push(new Schedule(null));
    };
self.removeSlot = function () { 
console.log('removed'); 
//self.schedules.remove(this);
self.doctor.schedules.remove(this);
} 
}; 
var viewModel = new vm(); 
ko.applyBindings(viewModel); 
$('#saveButton').click(function(){ 
    alert('savebutton'); 
    var testjson=ko.toJSON(viewModel.doctor); 
    console.log(testjson); 
    var formdata=new FormData(); 
    formdata.append("doctormetada",testjson); 
    console.log(projectUrl+"updateDoctor"); 
    $.ajax({ 
        url: projectUrl+"updateDoctor", 
        type: "POST", 
        data: formdata, 
        processData: false, 
        contentType: false, 
        success: function (res) { 
        formdata = new FormData(); 
            //self.doctor(new Doctor()); 
    } 
}); 
});
$('#appsave').click(function(){ 
    alert('savebutton'); 
    viewModel.doctor.password = "";
    //var testjson=ko.toJSON(viewModel.schedules); 
    var testjson=ko.toJSON( viewModel.doctor);
    console.log(testjson); 
    var formdata=new FormData(); 
    formdata.append("doctormetada",testjson); 
    console.log(projectUrl+"updateDoctor"); 
    $.ajax({ 
        url: projectUrl+"updateDoctor", 
        type: "POST", 
        data: formdata, 
        processData: false, 
        contentType: false, 
        success: function (res) { 
           formdata = new FormData(); 
           //self.doctor(new Doctor()); 
        } 
     });  
}); 

但是当我按下按钮时,我没有得到任何新的行,尽管console.log('added');得到执行。

谁能告诉我我做错了什么?

我认为这与您在vm函数中的doctor实例有关。我可以肯定的是,没有一个能暴露问题所在的司法系统。我拿走了你的代码,去掉了全局变量,然后强迫自己。医生是医生的一个例子。当addSlot被点击时,我添加了一个console.log来注销self.doctor.schedules的长度。

function vm() { 
    var self = this; 
    self.doctor = new Doctor(); // i changed this for the minute
    self.addSlot = function () { 
    //self.schedules.push(new Model.Schedule(null));
    console.log('added');
    self.doctor.schedules.push(new Schedule(null));
    console.log(self.doctor.schedules().length);
    ...   
}
这是我的小提琴:http://jsfiddle.net/davidoleary/s726e/

更新的小提琴:http://jsfiddle.net/davidoleary/SwLd7/您可以更改vm()以获得新的函数:

function vm() {
    var self = this;
    self.doctor = new Doctor();
    self.setDoctor = function (doc) {
      self.doctor.name(doc.name);
      //....
    };
    //self.schedules = ko.observableArray(schedules);
    self.addSlot = function (sched) {
        //self.schedules.push(new Schedule(null));
        self.doctor.schedules.push(sched);
    };
    self.removeSlot = function () {
        console.log('removed');
        //self.schedules.remove(this);
        self.doctor.schedules.remove(this);
    }
};
var viewModel = new vm();

你可以调用设置和addSlot在你的ajax成功回调(我已经模仿这使用setTimeout在新的fiddle):

success: function (...) { 
    viewModel.setDoctor(doctor);
    viewModel.addSlot(new Schedule());
}

你必须使用.push,正如@Dave所说,这将用新数据更新你的ViewModel。下面是完整的示例:

function ProductsViewModel() {
    var self = this;
    self.products = ko.observableArray();
    var baseUri = '@ViewBag.ApiUrl';
    // New code
    self.create = function (formElement) {
        // If the form data is valid, post the serialized form data to the web API.
        $(formElement).validate();
        if ($(formElement).valid()) {
            $.post(baseUri, $(formElement).serialize(), null, "json")
                .done(function (o) { 
                    // Add the new product to the view-model.
                    self.products.push(o); 
                });
        }
    }
    self.update = function (product) {
        $.ajax({ type: "PUT", url: baseUri + '/' + product.Id, data: product });
    }
    self.remove = function (product) {
        // First remove from the server, then from the view-model.
        $.ajax({ type: "DELETE", url: baseUri + '/' + product.Id })
            .done(function () { self.products.remove(product); });
    }
    $.getJSON(baseUri, self.products);
}