gpt4 book ai didi

javascript - 完全替换一个对象

转载 作者:行者123 更新时间:2023-11-30 20:43:36 26 4
gpt4 key购买 nike

我尝试替换 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com