【问题标题】:Is there a way to swap one polymer component for another?有没有办法将一种聚合物成分换成另一种?
【发布时间】:2014-08-01 13:56:13
【问题描述】:

我在概念上有点卡住了。我创建了一个构建器组件,用于通过 AJAX 帖子管理数据输入。返回时,我将拥有一个可以呈现给客户端的 JSON 对象。理想情况下,我想实例化一个新的渲染组件,将 JSON 对象传递给它,然后销毁构建器组件(二号门是一个简单的页面重新加载,但这似乎是 1990 年代的锤子,用于 21 世纪的钉子) .

代表性(简化)构建器组件:

<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/core-ajax/core-ajax.html">

<polymer-element name="post-builder" attributes="accesstoken">
    <template>
        <core-ajax id="poster" url="api_call" handleAs="json"></core-ajax>
        <textarea class="form-control" rows="4" placeholder="Enter text here." value="{{ body }}"></textarea>
        <div class="postControls">
            <div class="sendLink">
                <a href="javascript:null;" on-click="[[ postAndReplaceTile ]]">Post</a>
            </div>
        </div>
    </template>
    <script>
        created: function(){
            this.body = '';
        },
        ready: function(){

        },
        postAndReplaceTile: function(){
            data = {body : this.body, publish : true};

            var ajax = this.$.poster;
            ajax.removeEventListener('core-response');

            ajax.method = 'POST';
            ajax.contentType = 'application/json';
            ajax.params = { access_token: this.accesstoken };
            ajax.body = JSON.stringify(data);
            ajax.addEventListener('core-response', function(){
                if(this.response.hasOwnProperty('post')){
                    if(this.response.post.hasOwnProperty('id')){

                        // valid JSON object of the new post

                    }
                }
            }); 
            ajax.go();


        }
    });
    </script>
</polymer-element>

在有效 JSON 对象的阶段,我正在寻找 jQuery 的 replaceWith() 的道德等价物...认识到 JSON 对象在被替换的组件中,因此我需要仔细排序这些事件。有没有办法干净地到达父 DOM 并进行这些类型的转换?

【问题讨论】:

    标签: polymer


    【解决方案1】:

    您可以使用parentNode.host(请参阅here)来访问容器元素并使用DOM 方法来替换该元素,但这在某种程度上是一种反模式并破坏了封装(请参阅herehere) .

    使用events 并让容器元素负责交换元素可能会更好。

    【讨论】:

    • 这真的很有帮助,谢谢。我想我已经超越了这个概念,现在正在努力构建具有创建、编辑和显示视图的组件,这些组件都是自包含的。只是不断地从 jQuery 转变思路...
    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2022-12-24
    • 2014-11-04
    • 2011-01-04
    相关资源
    最近更新 更多