Pergunta

Eu estou usando as recomendações estabelecidas aqui para baixo ( http://www.odetocode.com /articles/473.aspx ) para escrever um AJAX JavaScript webchat sistema usando simulado namespacing e prototipagem.

Em um dos meus métodos de protótipo Eu estou chamando o $. Ajax método em jQuery . O que então quero fazer é passar os dados JSON retornados em um método dentro de meu JavaScript webchat namespace.

O problema parece ser porque eu criei uma instância do meu webchat JavaScript, não pode chamar diretamente um método dentro dela, porque eu preciso abordá-la através do exemplo.

A parte fundamental no código abaixo é

            success: function(data, textStatus) {
                this.GetUpdate_Success(data)
            },

Estou pensando porque estamos dentro do método $ .ajax (), que este não se refere mais ao nosso objeto WebchatV3.

O código JavaScript completo é mostrado abaixo:

/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />

// Simulated 'namespace'
var AvonAndSomerset = {}

// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
    this.Members = new Array(); // Members in the chatroom
    this.Questions = new Array(); // The questions queue in the chatroom

// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);

    // Set-up AJAX defaults
    $.ajaxSetup({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" });
}

AvonAndSomerset.WebchatV3.prototype =
{
    // Get latest Member,Quetsion,Transcript and Room data from server
    GetUpdate: function(StartUp) {

        $.ajax({ url: "JSON.aspx/Members_GetChanges",
            data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
            success: function(data, textStatus) {
                this.GetUpdate_Success(data)
            },
            error: function(result) {
                alert('Members_GetChanges() failed: ' + result.responseText);
            }
        });
    },
    // Callback - on success of GetUpdate()
    GetUpdate_Success: function(data) {
        alert('The AJAX call was successful!');
    },
    // Does the MemberID exist in the local array?
    Members_DoesExist: function(MemberID) {
        alert('Searching for ' + MemberID);

        alert(this.Members.length);
    }
Foi útil?

Solução

A maneira mais fácil de corrigir isso é para criar uma variável que as referências this no âmbito adequado necessário. this e trabalho de âmbito diferente em javascript, em seguida, a maioria das línguas, neste caso, está se referindo ao objeto que está sendo passado para a função.

// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
    //here
    var self = this;
    $.ajax({ url: "JSON.aspx/Members_GetChanges",
        data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
        success: function(data, textStatus) {
            self.GetUpdate_Success(data)
        },
        error: function(result) {
            alert('Members_GetChanges() failed: ' + result.responseText);
        }
    });
},

Outras dicas

Tente

        success: function(data, textStatus) {
            AvonAndSomerset.WebchatV3.GetUpdate_Success(data)
        },

que pode funcionar.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top