KnockoutJS - 使用简单的选择输入绑定问题

时间:2016-01-12 00:23:34

标签: javascript jquery ajax knockout.js

我是新来的论坛和学习淘汰赛。我遇到了如何正确绑定选择输入并将其保存到ajax调用的问题。到目前为止,我使用简单的输入将2路绑定工作正常。我只是想获得一些指导,以及如何正确地将其保存到ajax并从ajax中检索数据并填充数据。

只是寻找提示或者是否有人有任何例子可以查看。我真的很感激。

HTML:

<select data-bind="options: available_exploitants_HPSM" multiple="true"></select>
<input data-bind="value: test">
<input data-bind="value: test2">

这是我的观点模型:

incidentViewModel = function IncidentViewModel() {
 var self = this;
 self.incidents = ko.observableArray();
 self.currentIncident = ko.observable();
 available_exploitants_HPSM = ko.observableArray(["1","2","3"]);


self.fetchdata = function() {
 $.getJSON(Incident.BASE_URL+filterlist+orderlist,
 function(data) { 
 if (data.d.results) { 
 self.incidents(data.d.results.map(function(item) {
 return new Incident(item);
 }));
 $('#loading').hide("slow");
 $('#IncidentTable').show("slow");
 }else {
 console.log("no results received from server");
 }
 });
    }


self.saveorupdate = function() {
 var id = this.ID,
 url = Incident.BASE_URL + (id ? '(' + encodeURIComponent(id) + ')' : '');
 console.log(url);
 return $.ajax(url, {
 type: id ? "MERGE" : "POST",
 data: ko.toJSON({
 test: this.Description,
 test2: this.Incident,
 composante: this.composante
 }),
 processData: false,
 contentType: "application/json;odata=verbose",
 headers: "accept": "application/json;odata=verbose","If-Match": "*",
 success: function (data) {
 incidentViewModel.fetchdata();

 } 
 });
 }
}


function Incident(data) {
var self = this;
self.composante = ko.observable(data.composante);
self.test= ko.observable(data.test);
self.test2= ko.observable(data.test2);

}


var incidentViewModel = new IncidentViewModel();
ko.applyBindings(incidentViewModel);

1 个答案:

答案 0 :(得分:0)

我会做出的改变:

1)在incidentViewModel

...
return new Incident(item, self);
...

2)将saveorupdate移至Incident模型并将其编辑为:

function Incident(data, viewmodel) {
    var self = this;
    self.composante = ko.observable(data.composante);
    self.test = ko.observable(data.test);
    self.test2 = ko.observable(data.test2);
    self.id = data.id // you need id to use below in ajax
    self.saveorupdate = function() {
        var id = self.id, // changed to 'self'
            url = Incident.BASE_URL + (id ? '(' + encodeURIComponent(id) + ')' : '');
        console.log(url);
        return $.ajax(url, {
            type: id ? "MERGE" : "POST",
            data: {
                test: self.test(), //Description,
                test2: self.test2(), //Incident,
                composante: self.composante() // changed to 'self'
            },
            processData: false,
            contentType: "application/json;odata=verbose",
            headers: "accept": "application/json;odata=verbose",
            "If-Match": "*",
            success: function(data) {
                viewmodel.fetchdata();
            }
        });
    }

}