【问题标题】:How to access tag attribute in spacebar如何访问空格键中的标签属性
【发布时间】:2016-11-10 23:32:38
【问题描述】:

如何从标签中获取属性值,如宽度、颜色、值...

<template>
   {{#if body.width > 979px }}
      {{> tmp1 }}
   {{else}}
      {{> tmp2 }}
   {{/if}}
</template>

<template name="tmp1">...</template>
<template name="tmp2">...</template>

【问题讨论】:

  • 你做了哪些研究?你试过什么?
  • 我发现的唯一方法是制作动态模板,然后在 onRendered 事件中使用 js 获取这些值,但卡在窗口调整大小事件中。

标签: meteor spacebars


【解决方案1】:

您不能直接从空格键模板访问标签属性。您需要为此创建一个模板助手。

Template.templateXY.helpers({
   bigBody: function() {
      return $("body").width() > 979;
   }
});

然后你像这样使用它:

<template name="templateXY">
   {{#if bigBody}}
      {{> tmp1}}
   {{else}}
      {{> tmp2}}
   {{/if}}
</template>

更新:要让助手重新计算窗口大小调整事件,您需要稍微修改一下。您可以为此使用 Dependency 对象。

Template.templateXY.onCreated(function() {
   // create a dependency
   this.resizeDep = new Dependency();
});

Template.templateXY.onRendered(function() {
   let tmpl = this;
   // invalidate the dependency on resize event (every 200ms)
   $(window).on("resize.myEvent", _.throttle(function() {
      tmpl.resizeDep.changed();
   }, 200));
});

Template.templateXY.helpers({
   bigBody: function() {
      // recompute when the dependency changes
      Template.instance().resizeDep.depend();
      return $("body").width() > 979;
   }
})

Template.templateXY.onDestroyed(function() {
   $(window).unbind("resize.myEvent");
});

其他可能的解决方案是将窗口宽度存储到 ReactiveVar(它本身就是一个响应式数据源)并使用 .on("resize", fn) 来更改 ReactiveVar

【讨论】:

  • 是否会在 body 宽度发生变化时更新,例如在调整窗口大小时?
  • 不,我用反应式版本更新了答案。看看它是否对你有帮助。
【解决方案2】:

经过一番研究,我发现没有空格键合适的解决方案,最好的选择是使用js代码。

代码如下:

Session.set("width", $(window).innerWidth());
window.onresize = function () { Session.set("width", $(window).innerWidth()); };

if(Meteor.isClient) {
    Template.body.helpers({ 'dynamicTemplateName': function () { return Session.get("width"); } });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-03
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多