mcbowes
mcbowes

Reputation: 798

Knockout mapping adding a function

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}
]

Upvotes: 1

Views: 658

Answers (1)

Anders
Anders

Reputation: 17564

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)')));

Upvotes: 2

Related Questions