聚合物 如何使用条件根据函数返回的布尔值显示不同的元素



我一直在尝试解决这个问题,但没有成功。

我的代码是:

[...]
    <script src="lib/webcomponentsjs/webcomponents-lite.min.js"></script>
    <link rel="import" href="lib/polymer/polymer.html">
    <link rel="import" href="components/app-layout.html">
    <link rel="import" href="components/disconnected-layout.html">
</head>
<body unresolved>
    <template>
        <script>
        Polymer({
            connected: function() {
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open( "GET", "127.0.0.1:5021", false );
                xmlHttp.send( null );
                var connection = JSON.parse(xmlHttp.responseText);
                if (connection.success == undefined)
                {
                    return false;
                }
                return !!connnection.success;
            }
        });
        </script>
[...]

上面的这一部分检查与服务器的连接。

在下一部分应该选择正确的显示:

[...]
        <template is="dom-if" if="{{connected()}}">
            <app-layout></app-layout>
        </template>
        <template is="dom-if" if="{{!connected()}}">
            <disconnected-layout></disconnected-layout>
        </template>
[...]

但是,不是连接/断开连接的布局浏览器显示空白页。我该如何解决这个问题?

聚合物绑定用于绑定到属性或"计算属性",它们是在更改某些其他属性时从函数动态生成的属性。

您可以尝试这样的普通属性:

Polymer({
  properties: {
    connected: {
      type: Boolean,
      value: function() {
        // code which returns true/false depending on whether you're connected
      }
    }
  }
});

当 Polymer 创建元素时,它将运行该函数来确定 connected 属性的初始值,然后可以绑定到示例中的初始值。请务必注意,这是计算一次的,因此如果您的客户端稍后脱机connected将不会更新。

计算属性是类似的,只是它们允许您在属性所依赖的元素上定义其他属性:

Polymer({
  properties: {
    otherProperty: String,
    connected: {
      type: Boolean,
      computed: '_isConnected(otherProperty)'
    }
  },
  _isConnected: function(otherProperty) {
    return otherProperty !== null;
  }
})

这将导致您的媒体资源在其他媒体资源发生更改时随时更新。

根据您的应用程序,您可能希望订阅浏览器的联机和脱机事件以动态更新此内容,并在事件处理程序中为此设置connected truefalse

看起来您有用于检测连接的特定逻辑:从计算机上运行的服务器查找响应。您可能最终需要创建一个间隔(setInterval)来定期检查并相应地更新属性。

最新更新