需要緩存的實時參考window.innerWidth(App.Utils.viewportWidth),然後使用不斷變化值作爲一個布爾值來控制流量執行你的頭函數(App.Header.watchHeader)。
var App = window.App || {};
(function($) {
App.Utils = {
breakpointMobile: 500,
viewportWidth: null,
init: function() {
$(window).on('load', $.proxy(this.listenViewportResize, this));
$(window).on('resize', this.debounce($.proxy(this.listenViewportResize, this), 200, false));
},
// taken from underscore
debounce: function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
},
listenViewportResize: function() {
App.Utils.viewportWidth = window.innerWidth;
$(window).trigger('utils:viewportChanged');
}
};
$($.proxy(App.Utils.init, App.Utils));
}(jQuery));
(function($) {
App.Header = {
init: function() {
$(window).on('utils:viewportChanged', $.proxy(this.watchHeader, this));
},
watchHeader: function() {
if (App.Utils.viewportWidth < App.Utils.breakpointMobile + 'px') {
// do your mobile thing
} else {
// do your desktop thing
}
}
};
$($.proxy(App.Header.init, App.Header));
}(jQuery));
謝謝Elise。我將給出這個結果 – JCHASE11 2014-11-22 04:00:36
你必須適應你的實現,但這裏唯一真正的複雜性是實現對window.innerWidth的動態引用 – 2014-11-22 04:02:10