我有一个自定义元素<test-object>
,如下所示:
@PolymerRegister('test-object')
class TestObject extends PolymerElement with TestBehavior {
TestObject.created() : super.created() {
}
}
TestBehavior
:
@reflectable
class TestModel extends JsProxy {
@Property(notify: true)
num value = 0;
PolymerElement _target;
TestModel(PolymerElement target) {
_target = target;
}
changeBy(num by) {
value += by;
_target.set('testModel.value', value);
}
}
@behavior
abstract class TestBehavior implements PolymerBase {
@Property(notify: true)
TestModel testModel;
PolymerElement _instance;
static ready(instance) {
instance._init(instance);
}
static created(instance) {
instance._instance = instance;
}
_init(PolymerElement instance) {
set('testModel', new TestModel(instance));
}
}
我的主应用程序看起来像这样:
<dom-module id="main-app">
<style>
:host {
display: block;
@apply(--layout-center-center);
}
</style>
<template>
<div>{{testObject.testModel.value}}</div>
<test-object id="obj"></test-object>
</div>
</template>
</dom-module>
@PolymerRegister('main-app')
class MainApp extends PolymerElement {
@Property(notify: true)
TestObject testObject = null;
MainApp.created() : super.created();
ready() {
set('testObject', testObject = $$('#obj') as TestObject);
}
@Listen('click')
clicked([_]) {
testObject.testModel.changeBy(1);
}
@Observe('testObject.testModel.*')
valueChanged([_]) {
window.console.log('Value was changed');
}
}
这是一个非常简单的玩具示例。我单击<main-app>
,这会导致testModel中的值增加(这可行)。但是,<main-app>
不会更新应显示该值的div。此外,永远不会调用valueChanged
。
我想通知testObject
value
testModel
更新main-app
并将此通知传播到TempVar = 0
def rawEncode(input):
if TempVar == 0:
input = raw_input("GIVE ME SUPER SECRET MESSAGE TO ENCODE")
TempVar = TempVar + 1
unencoded = "%s" % input[:]
if "%s" % input == '':
return ''
else:
answer = ord("%s" % input[0])
return answer
,而不应通过数据绑定更新其UI。
为什么这不起作用?
答案 0 :(得分:0)
您不能在模型类中拥有属性,只能在组件
中拥有属性@Property(notify: true)
num value = 0;
应该只是
@reflectable
num value = 0;
答案 1 :(得分:0)
应该从元素类中调用set
和notifyPath
方法,而不是模型。这实际上简化了您的代码,并使一切工作也按预期工作。下面我粘贴了新的MainApp
,TestModel
和TestBehavior
类(我还做了一些其他的小编辑)。
@PolymerRegister('main-app')
class MainApp extends PolymerElement {
// Defines a read-only property (implicit because of the getter).
@property
TestObject get testObject => $['obj'];
MainApp.created() : super.created();
// I added the 2nd optional argument here, to fix a reflectable error
@Listen('click')
clicked([_, __]) {
// Notify directly here, this is the primary change.
notifyPath('testObject.testModel.value', testObject.testModel.changeBy(1));
}
@Observe('testObject.testModel.*')
valueChanged([_]) {
window.console.log('Value was changed');
}
}
// Removed the `_instance` field.
class TestModel extends JsProxy {
// use @reflectable instead of @Property(notify: true)
@reflectable
num value = 0;
TestModel();
num changeBy(num by) {
value += by;
// Added a return value for convenience
return value;
}
}
@behavior
abstract class TestBehavior implements PolymerBase {
@Property(notify: true)
TestModel testModel = new TestModel();
}