Polymer 观察聚合物JS中对象的更改

Polymer 观察聚合物JS中对象的更改,polymer,Polymer,我有一个带有模型对象的元素,我想观察如下: <polymer-element name="note-editor" attributes="noteTitle noteText noteSlug"> <template> <input type="text" value="{{ model.title }}"> <textarea value="{{ model.text }}"></textarea> &l

我有一个带有模型对象的元素,我想观察如下:

<polymer-element name="note-editor" attributes="noteTitle noteText noteSlug">
  <template>
    <input type="text" value="{{ model.title }}">
    <textarea value="{{ model.text }}"></textarea>
    <note-ajax-button url="/api/notes/" method="POST" model="{{model}}">Create</note-ajax-button>
  </template>

  <script>
    Polymer('note-editor', {
      attached: function() {
        this.model = {
          title: this.noteTitle,
          text: this.noteText,
          slug: this.noteSlug
        }
      },
    });
  </script>
</polymer-element>

创造
聚合物(“注释编辑器”{
附:函数(){
该模型={
标题:this.noteTitle,
text:this.noteText,
鼻涕虫:这个,鼻涕虫
}
},
});
我想观察模型中的变化,但显然不可能在元素和noteajaxbutton元素中使用modelChanged回调。怎么了?我该怎么做

我试着分开观察田野,但一点也不干净。您在那里看到的按钮元素的状态应该根据模型状态而变化,因此我需要关注对象的变化,而不是属性的变化。
谢谢

要观察对象中的路径,需要使用
observe
块:

Polymer('x-element', {
  observe: {
    'model.title': 'modelUpdated',
    'model.text': 'modelUpdated',
    'model.slug': 'modelUpdated'
  },
  ready: function() {
    this.model = {
      title: this.noteTitle,
      text: this.noteText,
      slug: this.noteSlug
    };
  },
  modelUpdated: function(oldValue, newValue) {
    var value = Path.get('model.title').getValueFrom(this);
    // newValue == value == this.model.title
  }
});

或者,您可以向模型添加一个额外的属性,例如“刷新”(布尔值),每次修改某些内部值时,也可以通过设置“刷新=”来修改它!刷新,则可以只观察一个属性而不是多个属性。当模型包含多个嵌套属性时,这是一个很好的例子

Polymer('x-element', {
  observe: {
    'model.refresh': 'modelUpdated'
  },
  ready: function() {
    this.model = {
      title: this.noteTitle,
      text: this.noteText,
      slug: this.noteSlug,
      refresh: false
    };
  },
  modelUpdated: function(oldValue, newValue) {
    var value = Path.get('model.title').getValueFrom(this);
  },
  buttonClicked: function(e) {
    this.model.title = 'Title';
    this.model.text = 'Text';
    this.model.slug = 'Slug';
    this.model.refresh = !this.model.refresh;
  }
});

在这种情况下,我要做的是使用*字符观察数组中的任何属性更改,这里是我的JSON对象的一个示例:

{
    "config": { 
        "myProperty":"configuraiont1",
        "options": [{"image": "" }, { "image": ""}]
     }
};
我创建了一个方法\u myFunctionChanged并将其作为参数config.options.传递,然后数组options中的每个属性都会在函数\u myFunctionChanged中观察到

Polymer({ 
 observers: ['_myFunctionChanged(config.options.*)'] 
});

您可以对对象使用相同的模式,而不是使用类似于config.options的数组。您只需观察config即可。

谢谢!这就是我尝试过的,但是如果不指定路径,就不可能观察完整对象的路径?例如,当我添加一个新属性时,我必须将它添加到带有该建议的observe块中,不是吗?
Object.observe()
只允许您观察顶级属性。例如,如果在
x={a:{b:{c:'foo;}}}}
中更改属性
c
o.o()
不会观察到该更改
observe js
,Polymer的库位于
o.o()
之上,增加了对观察对象深刻变化的支持。观察是否支持任何类型的通配符?比如“model.*”或“model[*].value”?当“model”是数组时,这尤其有用。数组/对象:。这里有一个技巧,在模板重复中,通过对象数组添加过滤器:{{obj.property | modelUpdated}}}if将对每个属性更改做出反应。