观察Polymer JS中对象的更改 [英] Observe changes for an object in Polymer JS

查看:87
本文介绍了观察Polymer JS中对象的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要观察的模型对象元素,如下所示:

I have an element with a model object that I want to observe like so:

<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>

我想观察模型中的变化,但是显然不可能在元素中以及在note-ajax-button元素中都不能使用modelChanged回调.怎么了?我该怎么办?

I want to observe changes in the model but apparently it's not possible to use modelChanged callback in the element and neither in the note-ajax-button element. What is wrong? How can I do that?

我尝试过单独观察这些字段,但这根本不干净.您在此处看到的按钮元素的状态应根据模型状态而变化,因此我需要注意对象(而不是属性)的变化. 谢谢!

I've tried observing the fields separately, but it's not clean at all. The state of the button element you see there should change depending on the model state, so I need to watch changes for the object, not the properties. Thanks!

推荐答案

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

To observe paths in an object, you need to use an observe block:

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
  }
});

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

这篇关于观察Polymer JS中对象的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆