Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  155] [ 2]  / answers: 1 / hits: 17538  / 10 Years ago, mon, march 10, 2014, 12:00:00

When the page loads I get the data by calling getGeneJSONData() and when I do a database udpate i call the same method to load the new data and I get the error You cannot apply bindings multiple times to the same element



Here's the code snips



    var geneViewModel = null;

var Gene = function (data) {
data = data || {};

var self = this;
self.geneValue = data.GeneValue;
self.geneCode = ko.protectedObservable(data.GeneCode);
self.geneName = ko.protectedObservable(data.GeneName);
self.geneComments = ko.protectedObservable(data.GeneComments);

};

var ViewModel = function (items) {
var self = this;
var newGene = { geneValue: , geneCode: ko.protectedObservable(null), geneName: ko.protectedObservable(null), geneComments: ko.protectedObservable(null) };

self.genes = ko.observableArray(ko.utils.arrayMap(items, function (data) {
return new Gene(data);
}));

self.updateGene = function (gene) {
getGeneJSONData();
}
}

function getGeneJSONData() {
$.ajax({
type: GET,
url: urlPath + '/GetGenes',
dataType: json
}).done(function (result) {
if (result) {
if (result.Success) {
var geneData = result.Data;

geneViewModel = new ViewModel(geneData);
ko.applyBindings(geneViewModel);

}

}
});
};

$(document).ready(function ($) {

getGeneJSONData();

});


I am not sure why I'm getting this error on the data reload. Do I have to remove the bindings before applying them again?


More From » knockout.js

 Answers
11

You only need to apply bindings once. Instead of creating a new ViewModel for AJAX request, just use the same ViewModel and update its properties.



I would suggest that you do this by applying your bindings in your document ready function and passing your ViewModel to your update function. Here is how I would do it:



var ViewModel = function(items) {
var self = this;
var newGene = {
geneValue: ,
geneCode: ko.protectedObservable(null),
geneName: ko.protectedObservable(null),
geneComments: ko.protectedObservable(null)
};

self.genes = ko.observableArray(ko.utils.arrayMap(items, function(data) {
return new Gene(data);
}));

//pass in view model here
self.updateGene = function(gene) {
getGeneJSONData(self);
}
}

function getGeneJSONData(viewModel) {
$.ajax({
type: GET,
url: urlPath + '/GetGenes',
dataType: json
}).done(function(result) {
if (result) {
if (result.Success) {
var geneData = result.Data;
viewModel.genes = result.Data

}

}
});
};

$(document).ready(function($) {
//apply bindings here
ko.applyBindings(geneViewModel);
getGeneJSONData();
});

[#72068] Saturday, March 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopherw

Total Points: 173
Total Questions: 107
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;