This is a migrated thread and some comments may be shown as answers.
reference view model from inside ajax success
3 Answers 100 Views
This is a migrated thread and some comments may be shown as answers.
Joshua
Top achievements
Rank 1
Joshua asked on 02 Aug 2012, 09:44 PM
I have created a view model that handles a button click. in that click it calls ajax. if the ajax call is successfull, i want to hide a div and show another one. inside of the ajax callback, i cannot use this to reference the view model. I know i can call the view model by name, but should I?


what is the proper way to code the below snippet?
var viewModel new kendo.observable({
    visibleEntrytrue,
    visibleSuccessfalse,
    hideEntryfunction(e{
        $.ajax('someurl').success(function(e{
            this.set("visibleEntry"false);
            this.set("visibleSuccess"true);
        });
    }
});

kendo.bind($('#divContainer')viewModel); 

3 Answers, 1 is accepted

Sort by
0
Joshua
Top achievements
Rank 1
answered on 08 Aug 2012, 04:05 PM
Another scenario where this is confusing is when you create a view model, which gets remote data and then you want to add the value back to the view model. can you use the extend to add thing?

var viewModel = new kendo.observable({
    viewData:{},
    visibleEntry: true,
    visibleSuccess: false,
    hideEntry: function(e) {
        $.ajax('someurl').success(function(result) {
            this.set("visibleEntry", false);
            this.set("visibleSuccess", true);
 
 
            this.viewData=result;
 
 
        });
    }
});
 
kendo.bind($('#divContainer'), viewModel);​

0
Accepted
Joshua Holt
Top achievements
Rank 2
answered on 09 Aug 2012, 05:37 PM
in the ajax callback, you are in a different scope.  A simple way around this is to create a closure:

var viewModel new kendo.observable({
    visibleEntrytrue,
    visibleSuccessfalse,
    hideEntryfunction(e{
    var self = this;  //create a local var to hold onto 'this' for use when the ajax returns
        $.ajax('someurl').success(function(e{
            self.set("visibleEntry"false); //use locally scoped variable rather than 'this' directly
            self.set("visibleSuccess"true)//use locally scoped variable rather than 'this' directly

        });
    }
});

Hope this helps!
-Josh
0
Joshua
Top achievements
Rank 1
answered on 10 Aug 2012, 01:20 AM
@Josh Thanks for the answer! Any chance you have some suggestions on the proper way to add data back the the viewModel when the call returns?

When i call extend or just set the property then i don't know if the property that i set will still be observable.
Tags
MVVM
Asked by
Joshua
Top achievements
Rank 1
Answers by
Joshua
Top achievements
Rank 1
Joshua Holt
Top achievements
Rank 2
Share this question
or