1
votes

I'm trying to add a function to a button on my form. I keep getting a message that alertMe is undefined.

I've tried to declare my mapping as such:

$(function () {

        var mapping = {
            create: function (options) {
                return new CsvImportItem(options.data);
            },
            alertMe: function () {
                alert('Here we go');
            }
        }


        var CsvImportItem = function (data) {
            ko.mapping.fromJS(data, {}, this);

            this.rowClass = ko.computed(function () {
                if (this.Accepted()) return 'success'; else return 'error';
            }, this);

            this.acceptItem = function () {
                this.Accepted(true);
            };

            this.declineItem = function () {
                this.Accepted(false);
            };

        }
        var viewModelJSON = ko.mapping.fromJS($.parseJSON('@Html.Raw(jsonData)'), mapping);

        ko.applyBindings(viewModelJSON);
    });

If I change the viewModelJSON to :

var viewModelJSON = ko.mapping.fromJS($.parseJSON('@Html.Raw(jsonData)'), {}, mapping);

then the alertMe function call works, but the rest of my display items do not. Any thoughts as to what I am doing wrong?

Update to show data structure

My data structure coming in to the view is of type

IEnumberable<Project.Namespace.CsvImportItem>

Therefore, I am getting a structure like so:

[
 {CsvImportItem},
 {CsvImportItem},
 {CsvImportItem}
]
1
Why do you want the mapping to add the alertMe? Why do just put the alertMe definition on the CsvImportItem object?nemesv
I want the function to work on the collection of CsvImportItems, not on the instance of 1 CsvImportItem like my functions rowClass, acceptItem, and declineItem. I'll update my post to make my data more clear.mcbowes

1 Answers

2
votes

You're trying to apply the json mapping to the mapping object, correct syntax

var viewModelJSON = ko.mapping.fromJS($.parseJSON('@Html.Raw(jsonData)'), mapping);

Also skip the mapping, its not needed for simple scenarios like these just do

ko.applyBindings(new CsvImportItem($.parseJSON('@Html.Raw(jsonData)')));