简体   繁体   中英

Polymer: observing path changes and deep path observation in declared properties

I'm using polymer (v1.1.5) with webcomponentsjs (v0.7.14) in Chrome (v45).

Unless I'm missing something, it looks like the Polymer code examples provided in the "Declared properties" section, under " Observing path changes " and " Deep path observation " are not working.

Observing path changes

Polymer({
  is: 'x-custom',
  properties: {
    user: Object
  },
  observers: [
    'userManagerChanged(user.manager)'
  ],
  userManagerChanged: function(user) {
    console.log('new manager name is ' + user.name);
  }
});

This is the result:

document.querySelector('x-custom').user // -> 'undefined'

I tried to initialize it differently:

Polymer({
  is: 'x-custom',
  properties: {
    user: {
      type: Object,
      value: function () {
        return {};
      }
    }
  },
  observers: [
    'userManagerChanged(user.manager)'
  ],
  userManagerChanged: function(user) {
    console.log('new manager name is ' + user.name);
  }
});

Now:

// -> Uncaught TypeError: Cannot read property 'name' of undefined

And even like this:

Polymer({
  is: 'x-custom',
  properties: {
    user: {
      type: Object,
      value: function () {
        return {manager: 'John'};
      }
    }
  },
  observers: [
    'userManagerChanged(user.manager)'
  ],
  userManagerChanged: function(user) {
    console.log('new manager name is ' + user.name);
  }
});

Result:

// -> new manager name is undefined
document.querySelector('x-custom').user.manager // -> "John"
document.querySelector('x-custom').user.manager = 'Paul' // -> "Paul"
// document.querySelector('x-custom').user.manager // -> "Paul"
// The property value has been updated, but the change has not been observed and no callback has been called

The same holds true for the code examples in "Deep path observation" .

Does anyone know how to fix this and get it working properly? Thanks!

You need to use this.set or this.notifyPath while changing path value such that observers are notified. Please read the below for more details.

https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#set-path

Below jsbin demonstrates observers for object path:

http://jsbin.com/qupoja/4/edit?html,output

In your case the below might work

document.querySelector('x-custom').set('user.manager','Paul')

In addition to that, as I mentioned in the comments, you have to modify the user manager observer to accept string as parameter rather than user object.

userManagerChanged: function(managerName) {
  console.log('new manager name is ' + managerName);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM