javascript - 完全替换一个对象

标签 javascript polymer polymer-1.0

我尝试替换 Polymer 元素中的完整对象(属性),我尝试了几种可能性,但没有一个真正有效...

这是我到目前为止的想法:

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));
}

如何在不为每个子属性调用 this.notifyPath("...") 的情况下将 this.child 替换为 r

最佳答案

为了观察对象和数组的变化,您可以使用与上面相同的方法。 ;

this.set('child',r);

在这里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>

关于javascript - 完全替换一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972938/

相关文章:

javascript - 扩展尚未创建的 javascript (nodeJS) 对象

javascript - `this` 的默认绑定(bind)与 Chrome 浏览器和 Node.js 不同

polymer - 类型错误 : Failed to execute 'contains' on 'Node' : parameter 1 is not of type 'Node Polymer

css - polymer 如何在滚动时更改工具栏文本大小

javascript - Polymer:firebase DB 不使用 firebase-element 更新

css - 样式不适用于聚合物网络组件中的动态内容

javascript - 更改矢量形状的颜色 - Photoshop

javascript - jQuery:无法在 Chrome 上运行 $.get (http get)

angularjs - 如何使用 ng-polymer-elements 解耦 2 向绑定(bind)?

svg - 自定义图标未显示在铁图标中