yglodt
yglodt

Reputation: 14551

Replace an object completely

I try to replace a complete object (property) in a Polymer element, and I tried several possibilities, but none actually works...

Here is what I came up with so far:

prefill: function() {
    randomChild(function(r) {

        // Does not work
        var t = Object.assign(this.child, r); // r is an existing Child-object
        this.set("child", t);

        // Does not work
        this.child.firstName = r.firstName;

        // Works
        this.set("child.firstName", r.firstName);

        // Also works
        this.child.lastName = r.lastName;
        this.notifyPath("child.lastName");
    }.bind(this));
}

How can I just replace this.child with r without calling this.notifyPath("...") for each subproperty ?

Upvotes: 1

Views: 64

Answers (1)

Cappittall
Cappittall

Reputation: 3441

In order to observable changes in Object and Array, you may use the same as you did above. ;

this.set('child',r);

here DEMO

<html>
<head>
  <base href="https://polygit.org/polymer+:master/components/">
  <link href="polymer/polymer.html" rel="import">
  
  <link rel="import" href="iron-ajax/iron-ajax.html">
  <link rel="import" href="iron-list/iron-list.html">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
</head>
 <body>
  <web-app>test ( if you see 'test' message, necassary libraries could not loaded. Try this later and check dev tools.(F12) </web-app>

  <dom-module id="web-app">
  <template>
    <style>
      :host {
        display: block;
        height: 100%;
      }
    
    </style>
    <template is="dom-if" if="[[child]]">
          Name:  [[child.surname]], [[child.name]].  <br/>
    </template>
    
  
    
  </template>
    <script>
    HTMLImports.whenReady(function() {
      
    class WebApp extends Polymer.Element {
      static get is() { return 'web-app'; }
      static get properties() { return { 
         r:{
           type:Object,
           value() {return {};}
         }
      }};
      
       
    static get observers() { return ['checkDataToTransfer(r)']    };
      
    ready(){
      super.ready();
      Polymer.RenderStatus.afterNextRender(this, () => {
      var obj = {"name": "Bob", "surname":"Marley"};
      setTimeout(()=>{
          this.set('r', obj );
      },2000);
    }); }
                          
    checkDataToTransfer(r){
      console.log("Assigning to another object", r);

      this.set('child', r);
      
    }
 }
customElements.define(WebApp.is, WebApp); 
      
 });
</script>
</dom-module>
</body>
</html>

Upvotes: 1

Related Questions