若是须要监听属性值变化能够经过给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这个属性就会触发一次,另外若是值没有改变也是不会执行的。dom
能够在listeners
里面写事件,值为一个回调函数,写法和js同样,去掉on。函数
另外发现attrChange函数里面的第一个值为saythis
attrChange:function(e){ console.log(e); console.log('属性值已改为' + this.say); }
这种方法只能观察一个属性,若是须要观察多个属性的变化,能够用更为复杂的observers
code
<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
都改变的时候才会执行这个方法。server
若是只须要监听age
和sex
改变时就发生能够这样写。对象
updataSay(age,sex)
若是只写一个,那么和observer
是同样的。blog
监听一个对象的属性变化事件
<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>
监听数组的值变化ip
<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:类型