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

时间:2014-05-06 10:07:52

标签: javascript knockout.js knockout-2.0

这是我的按钮

<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');被执行,但我没有获得任何新行。

有人可以告诉我,我做错了什么?

2 个答案:

答案 0 :(得分:1)

我认为它与你在vm函数中的医生实例有关。 没有jsfiddle暴露确切的问题,我可以肯定。我已经采取了你的代码并删除了全局变量,并强迫self.doctor成为Doctor的一个实例。 我添加了一个console.log,用于在点击addSlot时注销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();

然后你可以在你的ajax成功回调中调用set和addSlot(我在新小提琴中使用setTimeout模仿了这个):

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

答案 1 :(得分:0)

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

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