-2

I am trying to create a basic app for creating and editing contact details - for the purposes of improving my JavaScript skills. For some reason I can't manage to pass variable data from one class to the next - I'm trying to implement something similar to an MVC just to get started before i move to backbone.js

Here's my code:

//App Model Class
var contactsAppModel = 
{
    contacts:contacts,
    /* App Methods */
    init: function()
    {
        var theDetails;
        //initiate App - pull App data
        $j.ajax({
            type: "post",
            url: "inc/contactsModel.php",
            dataType: "html",
            data: '',
            beforeSend: function(url,data) 
            {
                $j('#result').html('<img src="images/page-loader.gif" height="80px" width="80px">').fadeIn('slow');
            }, 
            success: function(data)
            {
                 this.contacts = data;
                 return this.contacts;
            }
        });
        //alert('From WithOut '+this.contacts);
    }

};

//App Class
var contactsApp = 
{
     //App Properties
    contactDetails:'',

     /* App Methods */
    init: function()
    {
        //populate App properties
        this.contactDetails = contactsAppModel.contacts;
        $j('#result').html('<p>Contact Details:</p>'+this.contactDetails).css({'border-color': 'red'}).fadeIn('slow');
        alert('From contactsApp: '+this.contactDetails);
    },

};

How can i access the contents of variable 'data' from the contactsAppModel inside of contactsApp class? I'm trying to implement and OO-based solution to running a Javascript powered App with AJAX - not a functional approach.

Geraldo Isaaks
  • 156
  • 1
  • 1
  • 20
  • Can you point to a line that is giving you trouble? What exactly are you trying to do? – Evan Davis Jun 18 '15 at 13:36
  • 1
    As a broad guess I'd say that you need to wait until your AJAX request resolves before you can do anything with the result. – Evan Davis Jun 18 '15 at 13:36
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Jun 18 '15 at 13:40
  • 1
    Try to add to your ajax an async: false – Romeo Jun 18 '15 at 13:42
  • @Xufox would it hurt to actually try giving a solution instead of taking the easy way out? I've been trying different 'solutions' all morning without success... – Geraldo Isaaks Jun 18 '15 at 13:43

1 Answers1

2

Maybe can put contactsAppModel.init(); on the first line of your contactsApp.init() method.

Khamill
  • 51
  • 7
Jim Gaudet
  • 36
  • 4