функция обратного вызова, похоже, не выполняется - PullRequest
0 голосов
/ 06 марта 2012

У меня есть следующий код, извлекающий объект JSON из github, и я пытаюсь добавить определенные части в массив.

function getTree(hash) {
    var pathToTree, returnedJSON;
    pathToTree = 'https://api.github.com/repos/myaccount/myrepo/git/trees/' + hash;
    $.ajax({
        accepts: 'application/vnd.github-blob.raw',
        dataType: 'jsonp',
        url: pathToTree,
        success: function (json) {
            returnedJSON = json;
        },
        error: function (error) {
            console.debug(error);
        }
    });
    return returnedJSON;
}

function parseTree(hash) {
    var objectedJSON, objectList = [], i, entry;
    objectedJSON = getTree(hash, function () {
        console.debug(objectedJSON);                    // this is not appearing in console
        for (i = 0;  i < objectedJSON.data.tree.length; i += 1) {
            entry = objectedJSON.data.tree[i];
            console.debug(entry);
            if (entry.type === 'blob') {
                if (entry.type.slice(-4) === '.svg') {     // we only want the svg images not the ignore file and README etc
                    objectList.append(i.content);
                }
            } else if (entry.type === 'tree') {
                    objectList.append(parseTree(getTree(entry.sha)));
            }
        }

    });
    return objectList;
}

$(document).ready(function () {
    var objects = parseTree('master', function () {
        console.debug(objects);
    });
});

У меня есть код для извлечения объекта JSON, но у меня возникают проблемы при попытке его разобрать (иначе говоря, вытащить нужные биты). Колбэки, которые я использую, похоже, не работают, и мне было интересно, может ли кто-нибудь их просмотреть и помочь мне.

В частности, можно ли добавить обратный вызов для любой функции, которую я выберу? Должен ли я что-нибудь сделать для этой функции?

Ответы [ 3 ]

1 голос
/ 06 марта 2012

Я исправил код, чтобы проиллюстрировать, как вы это сделаете.

function getTree(hash, cb) {
    // notice that I copy the callback and hash references to have access to them in this 
    // function's closure and any subsequent closures, like the success and error
    // callbacks.
    var pathToTree, returnedJSON, cb = cb, hash = hash;
    pathToTree = 'https://api.github.com/repos/myaccount/myrepo/git/trees/' + hash;
    $.ajax({
        accepts: 'application/vnd.github-blob.raw',
        dataType: 'jsonp',
        url: pathToTree,
        success: function (json) {
            returnedJSON = json;
            // if anything was passed, call it.
            if (cb) cb(json);
        },
        error: function (error) {
            console.debug(error);
            // an error happened, check it out.
            throw error;
        }
    });
    return returnedJSON;
}

function parseTree(hash) {
    var objectedJSON, objectList = [], i, entry;
    objectedJSON = getTree(hash, function (objectedJSON) {
        console.debug(objectedJSON);                    // this is not appearing in console
        for (i = 0;  i < objectedJSON.data.tree.length; i += 1) {
            entry = objectedJSON.data.tree[i];
            console.debug(entry);
            if (entry.type === 'blob') {
                if (entry.type.slice(-4) === '.svg') {     // we only want the svg images not the ignore file and README etc
                    objectList.append(i.content);
                }
            } else if (entry.type === 'tree') {
                    objectList.append(parseTree(getTree(entry.sha)));
            }
        }

    });
    return objectList;
}

$(document).ready(function () {
    var objects = parseTree('master', function () {
        console.debug(objects);
    });
});
1 голос
/ 06 марта 2012

Добавить второй параметр функции getTree.Что-то вроде

function getTree(hash, callback)

И используйте параметр "jsopCallback" в ваших настройках Ajax

$.ajax({
      ...
      jsopCallback: callback,
      ...
1 голос
/ 06 марта 2012

Насколько я понимаю, вы не передаете обратный вызов своим функциям:

function getTree(hash) {

И вы используете как:

objectedJSON = getTree(hash, function () {

Аналогично, эта функция не имеет параметра обратного вызова:

function parseTree(hash) {

И вы используете как:

var objects = parseTree('master', function () {

Измените ваши функции следующим образом:

function getTree(hash, fn) {  ...  }
function parseTree(hash, fn) {  ...  }

А затем позвоните fn, используя fn() при необходимости.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...