简体   繁体   English

在AJAX完成对象文字后执行函数

[英]execute function after AJAX complete object literal

I'm trying to add data to a dynamic modal. 我正在尝试将数据添加到动态模式。 The modal should only come into view once the data has been added to the model. 只有将数据添加到模型后,模态才应出现。 I have tried to achieve this using the line $.when(Ss.pieceInfo(piece)).then(Ss.showInfo()); 我试图使用$.when(Ss.pieceInfo(piece)).then(Ss.showInfo());行来实现这一点$.when(Ss.pieceInfo(piece)).then(Ss.showInfo()); but it seems both functions are executing at the same time. 但是似乎两个函数都同时执行。 What 什么

var Ss = {
    $modal: $('#piece-modal'),
    $title: $('.piece-title'),
    $artist: $('.piece-artist'),
    $info: $('.piece-info'),


    init: function() {
        this.bindEvents();
    },

    bindEvents: function() {
        $('.piece').on("click", function(e) {
            e.preventDefault();
            var piece = $(this).data('slug');

        //This doesn't seem to have any effect
            $.when(Ss.pieceInfo(piece)).then(Ss.showInfo());
        });
    },

    pieceInfo: function(piece) {
        console.log(piece);
        $.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

            $.each(data, function(key, val) { 
                Ss.$title.html(val.title);
                Ss.$artist.html(val.artist); 
                Ss.$info.html(val.text);
            })
        });
    },

    showInfo: function() {
        var height = $('.primary-info').height();
        console.log(height)
        Ss.$modal.addClass('modal-active')
        Ss.$modal.css('transform','translate3D(0, calc(100% - '+ height +'px), 0)');
    },
};

$(document).ready(function(){
    Ss.init();
});

That is because you are not returning the promise in the Ss.pieceInfo() method, causing it to be resolved instantly. 那是因为您没有在Ss.pieceInfo()方法中返回诺言,从而使诺言立即得到解决。 As per the documentation for $.when() : 根据$.when()的文档

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. 如果将单个参数传递给jQuery.when() ,而不是Deferred或Promise,它将被视为已解析的Deferred,任何附加的doneCallbacks都将立即执行。

To do that, you will have to change that method only very slightly: return the $.getJSON promise. 为此,您仅需稍作更改即可:返回$.getJSON承诺。

pieceInfo: function(piece) {
    return $.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

        $.each(data, function(key, val) { 
            Ss.$title.html(val.title);
            Ss.$artist.html(val.artist); 
            Ss.$info.html(val.text);
        })
    });
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM