Pregunta

This is my button

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

actually when this button is pressed,I want another row to be inserted.So I did following way

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

this is my full code

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

}); 

but when I press the button I do not get any new row though console.log('added'); gets executed.

Can someone please tell me what did I do wrong?

¿Fue útil?

Solución

I think its to do with your instance of doctor in the vm function. without a jsfiddle that exposes the exact problem I can be sure. I've taken your code and cut out the globals, and forced self.doctor to be an instance of Doctor. I added a console.log to log out the length of self.doctor.schedules as addSlot is clicked.

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

here's my fiddle: http://jsfiddle.net/davidoleary/s726e/

Updated Fiddle: http://jsfiddle.net/davidoleary/SwLd7/ you might be able to change vm() to have new functions:

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

you may then be able call the set and addSlot in your ajax success callback (I have mimicked this using setTimeout in the new fiddle):

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

Otros consejos

You must use .push, as @Dave told, this will update your ViewModel vith new data. Here is complete example:

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top