有条件地添加聚合物元素

时间:2017-06-09 11:30:17

标签: javascript polymer

我想在某些条件下添加聚合物元素。必须从服务器异步请求条件

request().done(function(msg){//msg is the answer from the server});

我在Polymer文档中找到了dom-if。如果我理解正确,我必须将属性或计算属性传递给if条件

<template is="dom-if" if="{{...}}></template>

我不知道如何将asynchronus方法调用与dom-if

结合使用
<template is="dom-if" if="{{request().done(...)}}></template>

编辑:

我想在不同页面上多次使用dom-if。所以我将它实现为具有条件函数的新行为

showElement(id: String)

<template is="dom-if" if="{{showElement(foo)}}"></template>

问题是,服务器请求是异步的,所以我无法在行为中返回答案:

showElement: function(id) {
  request(id).done(function(anwser) {
    return answer;   
  }
}

任何人都可以帮助我吗?

提前致谢

最诚挚的问候, 基督教

2 个答案:

答案 0 :(得分:2)

If the method handling your server response is in a context aware of the element containing your dom-if, you can set a property binded to your dom-if in it.

You declare a property in your element containing the dom-if, and set it to false by default.

//properties declaration...
showElement : {
    type:Boolean,
    value: false
}
//others properties and end of properties declaration...

You declare your dom-if to be binded on this property

<template is="dom-if" if="{{showElement}}">...</template>

And in your method handling the server response, something like that.

if(condition is met){
    this.showElement = true;
}

The last part suppose the context of your handling function is the one of your element containing the property and the dom-if.

If it isn't the case, I'll need more details on how the request is fired and handled to extend this response and explain how to retrieve it.

答案 1 :(得分:0)

如果你的服务器返回布尔值,那么它很简单。你可以简单地做:

<template is="dom-if" if="{{foo}}"></template>

这意味着,无论何时从服务器获得响应,您都必须将其设置为foo属性:this.set("foo", response...)。这是第一步。您没有提到何时要向服务器发送请求或频率。无论如何,你可以这样做,例如,当加载屏幕或其他什么时。那时Async不会成为问题。

使用行为很好。但不是return,而应该只将值设置为属性

摘要:当页面加载(或输入是更改,或用户按下按钮...)时,您在服务器上调用请求 - &gt;等待回应 - &gt;当响应到来时,将其设置为(例如)foo属性 - &gt;就是这样。

最后,foo的默认值应该是false

上面几乎提到了Arfost。他是对的,所以问题出在哪里

编辑

根据您的评论,您总是有1个ID,根据ID的值从服务器获得1个响应。因此,例如,如果ID为5,那么其他一些属性为true,此属性会根据Id的值更改。

所以,没有任何额外的代码,你可以这样做:

showElement: function(id, property, value) {
  if(value == undefined) {
    request(id).done(function(answer) {
      this.set(property, answer); 
    }
  }
}

和绑定将如下:

<template is="dom-if" if="{{showElement(someID, 'foo1', foo1)}}"></template>

假设属性foo1不存在。你不能声明它。这是最重要的,因为条件if(value == undefined)否则不会被调用。

只是为了解释showElement(someID, 'foo1', foo1)'foo1'(第二个参数)表示应存储来自服务器的响应的属性名称。 由于绑定,foo1(第三个参数)在这里。多亏了这一点,每当属性dom-if发生变化时,foo1都会被注意到。

我没有测试过,但我认为它可能有用。