Hey everyone, I'm struggling with my code and could really use some help. I'm new to knockout and encountering an issue. Initially, I receive JSON data from the database and it works fine. However, when I click 'Add some', I'm trying to push the same data from the database to my observable array, but the code below isn't working. Any suggestions would be appreciated. Error: Unable to process binding "text: function (){return AdId }"...
HTML:
<div data-bind="foreach: Ads">
<p data-bind="text: AdId"></p>
</div>
<div data-bind="click: addSome">Add some</div>
MODEL:
function AdListModel() {
var self = this;
self.Ads = ko.mapping.fromJS([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
self.InitialData = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.result(data); <---- works
}
});
}
self.addSome = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(data); <---- doesn't work
},
});
};
self.InitialData();
}
ko.applyBindings(new AdListModel());
I've already tried using
self.Ads.push(ko.mapping.fromJS(data))
but unfortunately, it didn't solve the problem.