Question

I'm stuck a bit conceptually. I've created a builder component for managing the input of data via an AJAX post. On return, I'll have a JSON object that I can render to the client. Optimally, I'd like to instantiate a new render component, pass the JSON object to it, and then destroy the builder component (door number two is a simple page reload, but that seems like a very 1990s hammer for a 21st century nail).

Representative (simplified) builder component:

<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>

At the stage of the valid JSON object, I'm looking for a moral equivalent of jQuery's replaceWith()...recognizing that the JSON object is in the component that's being replaced so I need to sequence these events carefully. Is there a way to cleanly reach up to the parent DOM and do these types of transformations?

Was it helpful?

Solution

You could use parentNode.host (see here) to access the container element and use DOM methods to replace the element but that's somehow an anti-pattern and breaks encapsulation (see here and here).

It's proably better to use events and let the container element take care of swaping the elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top