gpt4 book ai didi

javascript - 如何在只读 Polymer 1.x 属性中设置子属性

转载 作者:行者123 更新时间:2023-11-28 05:20:33 26 4
gpt4 key购买 nike

如何在 Polymer 中设置只读子属性而不完全替换其值?

Polymer({
is: 'my-element',

properties: {
foo: {
type: Object,
value: function() { return {bar:1, baz:2}; },
readOnly: true,
notify: true
}
},

observers: [
'_onBarChanged(foo.bar)', // this should fire
'_onBazChanged(foo.baz)' // this not
],

// how do I set this.foo.bar without completely replacing this.foo
ready: function() {
// the only way I found is completely replacing it's value
let temp = Object.assign({}, this.foo, {bar: 3});
this._setFoo(temp);
}
});

感觉好像错过了什么。

最佳答案

何时 updating an object's subproperty ,你应该使用this.set('foo.baz', value)而不是this.foo.baz = value以便发出更改通知。

HTMLImports.whenReady(() => {
Polymer({
is: 'x-foo',
properties: {
foo: {
type: Object,
readOnly: true,
value: () => ({bar: 2, baz: 4})
}
},
observers: [
'_barChanged(foo.bar)',
'_bazChanged(foo.baz)',
],
_barChanged: function(bar) {
console.log('bar', bar);
},
_bazChanged: function(baz) {
console.log('baz', baz);
},
_changeBar: function() {
this.set('foo.bar', this.foo.bar === 5 ? 3 : 5);
},
_changeBaz: function() {
this.set('foo.baz', this.foo.baz === 3 ? 5 : 3);
}
});
});
<head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<x-foo></x-foo>

<dom-module id="x-foo">
<template>
<div>bar: [[foo.bar]]</div>
<div>baz: [[foo.baz]]</div>
<button on-tap="_changeBar">Change bar</button>
<button on-tap="_changeBaz">Change baz</button>
</template>
</dom-module>
</body>

codepen

关于javascript - 如何在只读 Polymer 1.x 属性中设置子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591811/

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