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