Observe changes for an object in Polymer JS

前端 未结 3 1994
悲&欢浪女
悲&欢浪女 2021-01-05 15:52

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

         


        
相关标签:
3条回答
  • 2021-01-05 16:03

    Or you can add an extra attribute to your model called for example 'refresh' (boolean) and each time you modify some of the internal values also modify it simply by setting refresh = !refresh, then you can observe just one attribute instead of many. This is a good case when your model include multiple nested attributes.

    Polymer('x-element', {
      observe: {
        'model.refresh': 'modelUpdated'
      },
      ready: function() {
        this.model = {
          title: this.noteTitle,
          text: this.noteText,
          slug: this.noteSlug,
          refresh: false
        };
      },
      modelUpdated: function(oldValue, newValue) {
        var value = Path.get('model.title').getValueFrom(this);
      },
      buttonClicked: function(e) {
        this.model.title = 'Title';
        this.model.text = 'Text';
        this.model.slug = 'Slug';
        this.model.refresh = !this.model.refresh;
      }
    });
    
    0 讨论(0)
  • 2021-01-05 16:15

    what I do in this situation is use the * char to observe any property change in my array, here an example of my JSON object:

    {
        "config": { 
            "myProperty":"configuraiont1",
            "options": [{"image": "" }, { "image": ""}]
         }
    };
    

    I create a method _myFunctionChanged and I pass as parameter config.options.* then every property inside the array options is observed inside the function _myFunctionChanged

    Polymer({ 
     observers: ['_myFunctionChanged(config.options.*)'] 
    });
    

    You can use the same pattern with a object, instead to use an array like config.options. you can just observe config.

    0 讨论(0)
  • 2021-01-05 16:22

    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

    0 讨论(0)
提交回复
热议问题