Knockout JS-将数据绑定到我的表

Knockout JS - Issues binding data to my table

本文关键字:我的 数据绑定 JS- Knockout      更新时间:2023-09-26

嗨,伙计们,我对淘汰赛和边走边学很陌生。我设法通过jsfiddle在我的网站上重现了我试图实现的目标http://jsfiddle.net/N2zNk/49/.我复制了代码并将其放入我的网站,唯一的区别是我通过AJAX从服务器获取数据。

现在发生的情况是,我的表使用编辑按钮在表中创建了1行,但没有呈现任何文本绑定。我相信Ajax的某些问题导致了我的问题,但我不知道它是什么

有人知道吗?

控制台错误消息:

Uncaught ReferenceError: Unable to process binding "text: function (){return Incident }"
Message: Incident is not defined

HTML代码:

<table class="table table-bordered table-hover text-center" id="example2">
    <thead>
        <tr>
            <th width="30" class="text-center"><i class="fa fa-list-alt fa-4"></i></th>
            <th width="75" class="text-center"> Incident <i class="fa fa-ticket"></i> </th>
            <th width="65" class="text-center"> Priorité <i class="fa fa-balance-scale"></i> </th>
            <th width="70" class="text-center"> Composante <i class="fa fa-building-o"></i> </th>
            <th width="300" class="text-center"> Description <i class="fa fa-ellipsis-h"></i> </th>
            <th width="100" class="text-center"> Date de début <i class="fa fa-calendar"></i> </th>
            <th width="100" class="text-center"> Responsable <i class="fa fa-user"></i> </th>
        </tr>
    </thead>
    <tbody data-bind="template: { name: 'Incidents', foreach: dataFromServer() }" />
    </tbody>
</table>

我的模板代码:

<script type="text/html" id="Incidents">
<tr>
    <td class='over_flow_control'><button class='edit_button btn btn-default btn-sm' type='button' value='Edit' data-bind="click: $parent.editProduct"><i class='glyphicon glyphicon-edit'></i></button></td>
    <td class='over_flow_control' data-bind="text: Incident"></td>
    <td class='over_flow_control'><h4><span class='priorité_span' data-bind="text:PrioritéValue"></span></h4></td>
    <td class='over_flow_control' data-bind="text:Composante"></td>
    <td class='over_flow_control text-left' data-bind="text:Description"></td>
    <td class='over_flow_control Date_de_début_cell' data-bind="text:Date_de_début"></td>
    <td class='over_flow_control' data-bind="text:ResponsableValue"></td>    
</tr>
</script>

我的javascript代码:

<script type="text/javascript">
function load_incidents(ID, Description, Composante, Incident, ÉtatValue, PrioritéValue, Duré, Date_de_début, Date_de_fin, Groupe_Support_Prime, Autres_Groupe_Support_Prime, ResponsableValue, Impact, Temps_Consacré, Type_de_tempsValue, Journal_des_actions, Dépanage, Suivi, Ressources) {
    var self = this;
    this.ID = ID;
    this.Description = ko.observable(Description);
    this.Composante = ko.observable(Composante);
    this.Incident = ko.observable(Incident);
    this.ÉtatValue = ko.observable(ÉtatValue);
    this.PrioritéValue = ko.observable(PrioritéValue);
    this.Duré = ko.observable(Duré);
    this.Date_de_début = ko.observable(Date_de_début);
    this.Date_de_fin = ko.observable(Date_de_fin);
    this.Groupe_Support_Prime = ko.observable(Groupe_Support_Prime);
    this.Autres_Groupe_Support_Prime = ko.observable(Autres_Groupe_Support_Prime);
    this.ResponsableValue = ko.observable(ResponsableValue);
    this.Impact = ko.observable(Impact);
    this.Temps_Consacré = ko.observable(Temps_Consacré);
    this.Type_de_tempsValue = ko.observable(Type_de_tempsValue);
    this.Journal_des_actions = ko.observable(Journal_des_actions);
    this.Dépanage = ko.observable(Dépanage);
    this.Journal_des_actions = ko.observable(Journal_des_actions);
    this.Suivi = ko.observable(Suivi);
    this.Ressources = ko.observable(Ressources);
    //This is the start edit group//
    this.editDescription = ko.observable(Description);
    this.editComposante = ko.observable(Composante);
    this.editIncident = ko.observable(Incident);
    this.editÉtatValue = ko.observable(ÉtatValue);
    this.editPrioritéValue = ko.observable(PrioritéValue);
    this.editDuré = ko.observable(Duré);
    this.editDate_de_début = ko.observable(Date_de_début);
    this.editDate_de_fin = ko.observable(Date_de_fin);
    this.editGroupe_Support_Prime = ko.observable(Groupe_Support_Prime);
    this.editAutres_Groupe_Support_Prime = ko.observable(Autres_Groupe_Support_Prime);
    this.editResponsableValue = ko.observable(ResponsableValue);
    this.editImpact = ko.observable(Impact);
    this.editTemps_Consacré = ko.observable(Temps_Consacré);
    this.editType_de_tempsValue = ko.observable(Type_de_tempsValue);
    this.editJournal_des_actions = ko.observable(Journal_des_actions);
    this.editDépanage = ko.observable(Dépanage);
    this.editJournal_des_actions = ko.observable(Journal_des_actions);
    this.editSuivi = ko.observable(Suivi);
    this.editRessources = ko.observable(Ressources);
    //end of the edit group//
    this.accept = function () {
    this.Description(this.editDescription());
    this.Composante(this.editComposante());
    this.Incident(this.editIncident());
    this.ÉtatValue(this.editÉtatValue());
    this.PrioritéValue(this.editPrioritéValue());
    this.Duré(this.editDuré());
    this.Date_de_début(this.editDate_de_début());
    this.Date_de_fin(this.editDate_de_fin());
    this.Groupe_Support_Prime(this.editGroupe_Support_Prime);
    this.Autres_Groupe_Support_Prime(this.editAutres_Groupe_Support_Prime());
    this.ResponsableValue(this.editResponsableValue());
    this.Impact(this.editImpact());
    this.Temps_Consacré(this.editTemps_Consacré());
    this.Type_de_tempsValue(this.editType_de_tempsValue());
    this.Journal_des_actions(this.editJournal_des_actions());
    this.Dépanage(this.editDépanage());
    this.Journal_des_actions(this.editJournal_des_actions());
    this.Suivi(this.editSuivi());
    this.Ressources(this.editRessources());
    return true;
    }.bind(this);
    //reset to originals on cancel
    this.cancel = function () {
    this.editDescription(this.Description());
    this.editComposante(this.Composante());
    this.editIncident(this.Incident());
    this.editÉtatValue(this.ÉtatValue());
    this.editPrioritéValue(this.PrioritéValue());
    this.editDuré(this.Duré());
    this.editDate_de_début(this.Date_de_début());
    this.editDate_de_fin(this.Date_de_fin());
    this.editGroupe_Support_Prime(this.Groupe_Support_Prime);
    this.editAutres_Groupe_Support_Prime(this.Autres_Groupe_Support_Prime());
    this.editResponsableValue(this.ResponsableValue());
    this.editImpact(this.Impact());
    this.editTemps_Consacré(this.Temps_Consacré());
    this.editType_de_tempsValue(this.Type_de_tempsValue());
    this.editJournal_des_actions(this.Journal_des_actions());
    this.editDépanage(this.Dépanage());
    this.editJournal_des_actions(this.Journal_des_actions());
    this.editSuivi(this.Suivi());
    this.editRessources(this.Ressources());
    }.bind(this);
}
Incidents = {
pvm: {},
productStore: {
    products: [],
    init: function (data) {
        this.products = $.map(data, function (product) {
            return new load_incidents(product.ID, product.Description(), product.Composante());
        });
        console.log(this.products);
    }
},  
init: function () {
var self = this;
dataFromServer = ko.observableArray([]);
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
function (data) {
if (data.d.results) {
dataFromServer(JSON.stringify(data.d.results));
console.log(dataFromServer());
}
}
);
Incidents.productStore.init(dataFromServer());
},
productViewModel: function (data) {
        var self = this;
        var productsArray = [];
            productsArray = data;
        this.products = ko.observableArray(productsArray);
        this.selectedProduct = ko.observable();
        this.editProduct = function (productToEdit) {
            self.selectedProduct(productToEdit);
            // Incidents.pvm.selectedProduct(productToEdit);
        };
        this.acceptEdit = function () {
            var selected = Incidents.pvm.selectedProduct();
            if (selected.accept()) {
                Incidents.pvm.selectedProduct("");
                $('#dialogEditProduct').popup('close');
            }
        };
        this.cancelEdit = function () {
            Incidents.pvm.selectedProduct().cancel();
            Incidents.pvm.selectedProduct("");
            $('#dialogEditProduct').popup('close');
        };
    }
};
ko.bindingHandlers.jqButton = {
    init: function (element) {
        $(element).button();
    },
    update: function (element, valueAccessor) {
        var currentValue = valueAccessor();
        $(element).button("option", "disabled", currentValue.enable === false);
    }
};
ko.bindingHandlers.openProductDialog = {
    update: function (element, valueAccessor) {  
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value) {
            $.mobile.changePage("#dialogEditProduct", {
                role: 'dialog'
            });
            $("#dialogEditProduct").open();    
            // $("#dialogEditProduct").trigger('create');    
        }
    }
};
$.extend({
    isNumber: function (obj) {
        return !isNaN(parseFloat(obj)) && isFinite(obj);
    }
});
Incidents.init(); 
ko.applyBindings(Incidents);
</script>

看起来大部分问题都是您没有正确使用var self=this模式。

一个常见的JavaScript构造函数如下所示:

var MyVm = function() {
  this.name = ko.observable('John');
  this.age = ko.observable(23);
}

然后你这样称呼它:

var myVm = new MyVm();

当您开始添加函数时,这种模式会变得复杂,因为您必须小心如何绑定。

var MyVm = function() {
  this.name = ko.observable('John');
  this.age = ko.observable(23);
  this.incAge = function() {
    this.age(this.age()+1);
  };
}

根据您的操作方式,当您调用incAge时,它可能无法按预期工作,因为this可能与您的视图模型不同。这就是var self = this;模式存在的原因。但它是这样使用的:

var MyVm = function() {
  var self = this;
  self.name = ko.observable('John');
  self.age = ko.observable(23);
  self.incAge = function() {
    self.age(self.age()+1);
  };
  return self;
}

使用此模式,您不必担心如何调用incAge

你粘贴了太多的代码,所以很难看到确切的问题你应该仔细阅读:如何创建一个最小、完整和可验证的示例,这也将帮助你解决自己的问题。即便如此,我还是可以看出您没有正确使用该模式。开始使用它,如我的示例所示,不要忘记不可或缺的return self;。在你的例子中,你使用的是一个带参数的构造函数,它可能是这样的:

var MyVm = function(_name, _age) {
  var self = this;
  self.name = ko.observable(_name);
  self.age = ko.observable(_age);
  self.incAge = function() {
    self.age(self.age()+1);
  };
  return self;
}

为了完成我的回答,我可以看到您正在将大多数属性直接映射到具有相同名称的可观察器中。使用敲除映射可以节省大量时间和代码。

作为这个模式的一个例子,我向您展示了去删除链接。它在你的小提琴里不起作用。

你必须先更改你的html:

    <a href="#" data-bind="click: $parent.removeItem">Delete</a>

然后将removeItem()函数添加到ViewModel:

productViewModel: function (data) {
    var self = this;
    var productsArray = [];
    if (data && data.length > 0) {
        productsArray = data;
    }
    self.products = ko.observableArray(productsArray);
    this.selectedProduct = ko.observable();
    this.removeItem = function (productToRemove){
        self.products.remove(productToRemove);
    }

如果你尝试执行这个fiddle,你可以看到它会删除行。

如果您更改此行:

                self.products.remove(productToRemove);

这个:

                this.products.remove(productToRemove);

(唯一的变化是this对于self),它不起作用。

关于列表的Knockout教程对您非常有帮助。