0

I have a KnockoutJS view model which has a function I need to access. The ViewModel is populated initially and ko.applyBindings called. This all works fine.

The problem is when trying to call the viewModel.RefreshData() function from outside of the the ViewModel (i.e. from other JavaScript code).

Mozilla is reporting TypeError: viewModel.RefreshData is not a function. I think the problem may be related to the Knockout Mapping plugin 'overwriting' the function.

The code is as follows:

var EditorViewModel = function (data) {

    var _self = this;

    _self.Data = ko.observable('');        

    _self.LoadData = function () {
        _self.Data(new ChildViewModel(data));
    };

    _self.RefreshData = function (_data) {
        _self.Data(new ChildViewModel(_data));
    };

    _self.LoadData(data);

    return _self;

};

var ChildViewModel = function (data) {

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


// On first load with modelData from AJAX:
var viewModel = new EditorViewModel(modelData);
ko.applyBindings(viewModel);

// When refreshing with newModelData from AJAX call:
viewModel.RefreshData(newModelData); // ERROR IS THROWN HERE!

Note that a ChildViewModel is used in order that the data/view can be refreshed.

5
  • 1
    The description of the error does not seem to match the code you provided: in the error message, you try to call RefreshData on the constructor EditorViewModel instead of on the instantiated object viewModel.
    – janfoeh
    Feb 6, 2015 at 11:23
  • @janfoeh I've edited the question to correct this
    – Graham
    Feb 6, 2015 at 11:34
  • I tested with the code you provided and it's working fine: jsfiddle.net/nd80jfr7/1 Feb 6, 2015 at 11:34
  • 2
    @Graham you left out the actual AJAX call. I suspect that this is where your problem lies - viewModel is somehow out of scope there.
    – janfoeh
    Feb 6, 2015 at 11:36
  • @Graham I've added a few comments about issues I see in your code here, and have added a suggestion for an improved version here.
    – janfoeh
    Feb 6, 2015 at 11:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.