简体   繁体   English

在窗口调整大小时更改骨干视图模板

[英]Change Backbone view template on window resize

I want to change the template of a view on window resize, to make it responsive. 我想更改窗口调整大小视图的模板,以使其响应。 This works fine when reloading the page, but I cannot update the template dynamically. 重新加载页面时此方法工作正常,但我无法动态更新模板。 As per the documents I have used this to set the template on page load: 根据文档,我使用它来设置页面加载时的模板:

getTemplate: function() {
    if ($(window).width() > 1024){
        this.desktopLayout = true;
        return '#MenuView';
    } else {
        this.desktopLayout = false;
        return '#MenuViewTablet';
    }
},

This works fine when you navigate to the page, but when the function is called on 'resize', it doesn't update the template. 当您导航到页面时,此方法工作正常,但是在“调整大小”上调用该函数时,它不会更新模板。

The definitive answer here is to use Backbone's listenTo function to listen to the window resize event , make your changes in that event callback, and then ensure to call render to re-render the view . 最终的答案是使用Backbone的listenTo函数来监听窗口调整大小事件 ,在该事件回调中进行更改,然后确保调用render来重新渲染视图

The most crucial step and most common mistake when making changes to the HTML structure of an application using Backbone is not calling render . 使用Backbone更改应用程序的HTML结构时,最关键的步骤和最常见的错误 是不调用render If you use something like Marionette on top of Backbone, in certain circumstances your view will be automatically re-rendered when making such changes. 如果在骨干网顶部使用“木偶”之类的东西,则在某些情况下,进行此类更改时,视图将自动重新呈现。

In your ItemView : 在您的ItemView

onShow : function () {
  $(window).on("resize.myNamespace", _.throttle(_.bind(this.render, this), 50));
},
onClose : function () {
  $(window).off("resize.myNamespace");
}
  • Listen for window resize event 监听窗口调整大小事件
  • Throttle render calls because resize event is fired very rapidly 油门渲染调用,因为调整大小事件触发得非常快
  • Bind this reference for render call 绑定this引用以进行渲染调用
  • Re-render view on resize; 重新渲染视图以调整大小; (render will call getTemplate again) (渲染器将再次调用getTemplate
  • Use onShow event so the binding only happens after the view has been inserted into the DOM 使用onShow事件,以便仅在将视图插入DOM后进行绑定
  • Cleanup listener in onClose event to prevent errors later on, namespace to prevent collisions with other code. onClose事件中清除侦听器以防止以后出错,在名称空间中清除侦听器以防止与其他代码冲突。

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

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