Changing Properties

Another interesting detail is how to make changes in properties correctly.

If the property is simple value you can use assignment, for example:

this.someStringProperty = 'value'; // works

If you deal with properties which are objects or arrays and mutate them (that is change their properties or add new elements to array) you should use special API in order to notify Polymer data system about the changes.

Example of changing an object:

this.user.name = 'John'; // does not work

this.set('user.name', 'value'); // works

Example of changing an array:

this.users.push({name: 'John'}); // does not work

this.push('users', {name: 'John'}); // works

Also, if changes are out of your control or you want to trigger property effects for a batch of changes there are notifyPath and notifySplices methods:

this.user.name = 'John';
this.user.surname = 'Smith';
this.notifyPath('user.*');

If in some cases you use "=", then a further refactoring can easily break the correct behavior by mixing up the rules. So there are two patterns to eliminate the problem:

  • avoid mutation of complex properties (i.e. using immutable data patterns) - each time you need to change complex object you should replace the whole object;

  • always use set() instead of a simple value assignment.

This will guarantee that you won’t forget the rules and won’t break anything later because of refactoring.

What we have learned so far
  • Changes in sub-properties are not propagated automatically.

  • Component properties should be mutated by using a set of Polymer methods.