我正在尝试将数据添加到动态模式中。只有在将数据添加到模型后才能进入模态。我试图使用行$.when(Ss.pieceInfo(piece)).then(Ss.showInfo());
来实现这一点,但似乎两个函数同时执行。什么
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();
});
答案 0 :(得分:3)
这是因为您没有在Ss.pieceInfo()
方法中返回承诺,导致它立即得到解决。 As per the documentation for $.when()
:
如果将单个参数传递给
jQuery.when()
并且它不是Deferred或Promise,则将其视为已解决的Deferred,并且将立即执行任何附加的doneCallbacks。
为此,您必须非常轻微地更改该方法:返回$.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);
})
});
},