reference view model from inside ajax success

4 posts, 1 answers
  1. Joshua
    Joshua avatar
    82 posts
    Member since:
    May 2012

    Posted 02 Aug 2012 Link to this post

    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); 
  2. Joshua
    Joshua avatar
    82 posts
    Member since:
    May 2012

    Posted 08 Aug 2012 Link to this post

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

  3. Answer
    Joshua Holt
    Joshua Holt avatar
    23 posts
    Member since:
    Jan 2010

    Posted 09 Aug 2012 Link to this post

    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
  4. Joshua
    Joshua avatar
    82 posts
    Member since:
    May 2012

    Posted 09 Aug 2012 Link to this post

    @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.
Back to Top