观察Polymer JS中对象的更改

jav*_*sco 6 polymer

我有一个模型对象的元素,我想这样观察:

<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>
Run Code Online (Sandbox Code Playgroud)

我想观察模型中的变化,但显然不可能在元素中使用modelChanged回调,也不能在note-ajax-button元素中使用.怎么了?我怎样才能做到这一点?

我已经尝试过单独观察这些字段,但它根本不干净.您在那里看到的按钮元素的状态应该根据模型状态而改变,因此我需要观察对象的更改,而不是属性.谢谢!

ebi*_*del 11

观察对象的路径,你需要使用一个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
  }
});
Run Code Online (Sandbox Code Playgroud)

http://www.polymer-project.org/docs/polymer/polymer.html#observeblock

  • 谢谢!这就是我尝试过的,但是如果不指定路径就不可能观察到整个对象?例如,当我添加一个新属性时,我将不得不将它添加到带有该提议的观察块中,不是吗? (4认同)
  • 观察支持任何一种外卡吗?像'model.*'或'model [*] .value'?当'model'是一个数组时,这尤其有用. (3认同)