Polymer1.0 监听属性值的变化

2018/05/02 09:58
阅读数 156

如果需要监听属性值变化可以通过给observer赋值一个回调函数。

<say-Hello></say-Hello>
<dom-module id="say-Hello">
  <template>
    <h1>{{say}}</h1>
  </template>
</dom-module>
<script>
  Polymer({
    is:'say-Hello',
    properties:{
      say:{
        type:String,
        value:'hello',
        observer:'attrChange'
      }
    },
    listeners:{
      'click':'setAttr'
    },
    setAttr:function(){
      this.say = 'attr';
    },
    attrChange:function(){
      console.log('属性值已改成' + this.say);
    }
  })
</script>

当属性值发生改变时,就会触发这个回调函数,注意只有你一开始写了value这个属性就会触发一次,另外如果值没有改变也是不会执行的。

可以在listeners里面写事件,值为一个回调函数,写法和js一样,去掉on。

另外发现attrChange函数里面的第一个值为say

attrChange:function(e){
  console.log(e);
  console.log('属性值已改成' + this.say);
}

这种方法只能观察一个属性,如果需要观察多个属性的变化,可以用更为复杂的observers

 

<say-Hello></say-Hello>
<dom-module id="say-Hello">
  <template>
    <h1>{{userName}}</h1>
  </template>
</dom-module>
<script>
  Polymer({
    is:'say-Hello',
    properties:{
      userName:String,
      age:Number,
      sex:String
    },
    attached:function(){
      this.userName = '老王';
      this.age = 25;
      this.sex = '男';
    },
    observers:[
      'updataSay(userName,age,sex)'
    ],
    updataSay:function(userName,age,sex){
      console.log(userName,age,sex);
    }
  })
</script>

observers值是一个数组,数组里面可以写回调函数, 'updataSay(userName,age,sex)'意思是当userName&&age&&sex都改变的时候才会执行这个方法。

如果只需要监听agesex改变时就发生可以这样写。

updataSay(age,sex)

如果只写一个,那么和observer是一样的。

监听一个对象的属性变化

<say-Hello></say-Hello>
<dom-module id="say-Hello">
  <template>
    <input value="{{user.name::input}}">
  </template>
</dom-module>
<script>
  Polymer({
    is:'say-Hello',
    properties:{
      user: {
        type: Object,
        value: function() {
          return {'name':'请输入内容'};
        }
      }
    },
    observers:[
      'userNameChanged(user.name)'
    ],
    userNameChanged: function(name) {
      console.log('new name: ' + name);
    }
  })
</script>

监听数组的值变化

<x-custom></x-custom>
<script>
  Polymer({
    is: 'x-custom',
    properties: {
      users: {
        type: Array,
        value: function() {
          return [];
        }
      }
    },
    observers: [
      'usersAddedOrRemoved(users.splices)'
    ],
    usersAddedOrRemoved: function(changeRecord) {
      if(!changeRecord)return;
      console.log(changeRecord);
    },
    ready: function() {
      this.push('users', {name: "Jack Aubrey"});
    },
  });
</script>

通过传递splices我们可以查看数组里面的详细信息

index:指数,push的当前值
removed: 删除的数量
addedcount:插入的项目数。
object:项目
type:类型

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部