当屏幕宽度改变时,如何在“骨干木偶”中执行此操作,重新执行获取?现在,必须重新加载我的代码才能检查浏览器的宽度。

device = getDevice(); // returns desktop or mobile based on $(window).width();

if (device === 'desktop') {
  // let's pull desktop data
  this.desktop = new desktopItemModel({device: 'desktop'});
  this.desktopPromise = this.desktop.fetch();
}

if (device === 'mobile') {
  // let's pull mobile data
  this.mobile = new mobileItemModel({device: 'mobile'});
  this.mobilePromise = this.mobile.fetch();
}

this.allPromise = [desktopPromise, mobilePromise];

if (device === 'desktop') {
    $.when(this.desktopPromise).done(_.bind(function() {
        // do your desktop stuff
    }, this));
}
if (device === 'mobile') {
    $.when(this.mobilePromise).done(_.bind(function() {
        // do your mobile stuff
    }, this));
}

最佳答案

我认为您的代码可以从一些重组中受益。

var model;

function getData () {
  model = new Model(type: device)
  model.fetch().then(doStuff)
}

function doStuff () {
  if (model.type == 'desktop') {
    // desktop stuff
  } else {
    // mobile stuff
  }
}

window.addEventListener("resize", _.debounce(fetchData, 1000))
// some browsers trigger a lot of resize events, others just at the end
fetchData()

关于javascript - 屏幕尺寸更改时重新执行api调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32993963/

10-11 13:32