【问题标题】:Polymer bound property isn't updated聚合物绑定属性未更新
【发布时间】:2016-11-21 23:24:30
【问题描述】:

我正在为 Polymer 编写一个简单的 i18n 元素。这个想法是下载翻译,然后将其缓存在本地存储中。我对以下代码有疑问,几乎逐字逐句取自https://github.com/PolymerElements/app-storage#polymerappstoragebehavior

<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-ajax/iron-ajax.html">
<link rel="import" href="../app-storage/app-localstorage/app-localstorage-document.html">

<dom-module id="x-trans">
    <template>
        <iron-ajax id="ajax"
            handle-as="json"
            last-response="{{translation}}"
        ></iron-ajax>
        <app-localstorage-document session-only log id="localstorage"
            key="x-trans-translation"
            data="{{translation}}"
        >
    </template>
    <script>
        Polymer({
            is: 'x-trans',
            properties: {
                translation: {
                    type: Object,
                    value: {},
                    notify: true
                }
            });
    </script>
</dom-module>

在我看来,这应该:

  • 用默认值{}声明属性translation
  • 获取文件(URL在运行时配置)并将响应保存到translation
  • translation 的内容存储在本地存储中。

但是,在下面的测试中:

test('retrieving translated string', function() {
                        var element = fixture('ajax');
                        request = element.$.ajax.generateRequest();
                        server.respond();
                        expect(request.response).to.be.ok;
                        expect(request.response).to.be.an('object');
                        expect(request.response['Hello world!']).to.be.equal('World, hello!');
                    });

app-localstorage 日志输出:

Got stored value! undefined Object {  }

在我看来,translation 以某种方式保留了它的默认值,尽管被绑定,它应该根据文档对其进行更新。谁能告诉我我做错了什么?

【问题讨论】:

    标签: javascript polymer


    【解决方案1】:

    您显示的代码看起来是正确的(除了省略的iron-ajax URL 和server 的设置)。 (demo)

    几个注意事项:

    • translation 的默认值应该是一个返回空对象的函数。将其直接设置为对象会导致该对象在您元素的所有实例之间共享,这可能不是您想要的。

    • handle-as="json" 是多余的,因为这是默认设置

    我怀疑app-localstorage 的日志表明您得到一个空对象,因为您的模拟server 可能设置不正确。

    【讨论】:

    • 我也这么认为,但expect(request.response['Hello world!']).to.be.equal('World, hello!'); 并没有失败。但是,我注意到element.$.ajax.lastResponse 未定义。是不是错了,我应该调查什么才能找到原因?
    • 好吧,我发现这是 Iron-ajax 请求和响应的一种特殊行为......在我的测试结束时,element.$.ajax.loadingtrue,所以响应仍然没有以某种方式到达元素,lastResponse 未定义,translation 未绑定。抱歉打扰并感谢您的意见!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多