Search code examples
javascriptknockout.jsknockout-mvcknockout-3.0

KnockoutJS Calling ViewModel function from inside another function


I'm having the following ViewModel in which I have few functions. And I am trying to call another function located in the same ViewModel.

This is my ViewModel:

var UploadFileListVewModel = function() {
var self = this;

Inside I have an init function:

//initialize view model
this.init = function () {
    $.ajax({
        url: '/Files/LastUploadedFiles',
        type: 'POST',
        cache: false,
        data: {},
    }).done(function (result) {

        //doing stuff 
    });
}   

Sometime later on I perform an remove file operation and once it completed I want to run my init fuction again

self.removeFile = function(item)
{
    $('#fileModal').modal('hide'); //closing modal dialog       

    $.ajax({
        //url: '@Url.Action("RemoveFile", "Files")',
        url: '/Files/RemoveFile',
        type: 'POST',
        data: { 'file_id': self.fileToRemoveId() },
        cache: false
    }).done(function (result) {

    //doing stuff 
    this.init();

    });     
}

I'm getting an error this.init() is not a function.

I would really appreciate if somebody could point me into right direction on how to call this init() function or suggest any workaround.


Solution

  • The this keyword inside the callback function is not your ViewModel. That's why you created the self, so you can use it inside events, arrays, callback functions etc.

    So, you should change your code to self.init().