以编程方式更改属性值或将数据绑定到Polymer中

时间:2016-10-13 12:40:53

标签: data-binding properties polymer polymer-1.0

我正在尝试根据从网页网址中检索到的数字更改iron-ajax元素中的网址。为此,我创建了带有计算属性的URL,该属性采用了我检索的数字 我遇到的问题是我不知道如何以编程方式更改我的属性中的值(这将是附加到URL的数字)。为了解决这个问题,我尝试在HTML中设置Number,然后将数据绑定到属性。但是,我也无法让它工作。

当我在我的属性中硬编码userId的值时,一切正常,所以我认为错误必须与我的数据绑定有关。如果有人能指出我正在做错的方向,那就太棒了。但是,如果有更好的解决方案,例如以编程方式设置userId的值,请告诉我。

<dom-module id="my-profile-view">

  <template>
    <style></style>

    <iron-ajax
      auto
      id="requestSingleUser"
      url="{{url}}"
      handle-as="json"
      last-response="{{response}}"></iron-ajax>

    <span id="stdNr" userId="{{55}}"></span>

  </template>

  <script>
  Polymer({
    is: 'my-profile-view',

    properties: {
      route: Object,

      userId: {
        value: '',
        notify: true
      },

      url: {
        computed: 'computeURL(userId)'
      },

    },

    ready: function() {
      //Get's the URL and strips it down to the nuber
      var getUrl = window.location.href;
      var stdudentNumber = getUrl.split("/").pop();

      //Set the number to then bind it back to the value inside the properties
      var stdId = this.$$("#stdNr");
      stdId.setAttribute('userId','{{20}}');
    },

    computeURL: function(userId) {
      return['http://api.dev/user/' + userId];
    },

  });
  </script>
</dom-module>

1 个答案:

答案 0 :(得分:0)

有几个问题。

我认为应该是这样的

<span id="stdNr">[[userId]]</span>

您的userID属性未正确定义,应该是

 userId: {
   type: String,
   value: ''
 }

然后在准备好的功能中你会做这样的事情

ready: function() {
  //Get's the URL and strips it down to the nuber
  var getUrl = window.location.href;
  //Set the number to then bind it back to the value inside the properties
  this.userId = getUrl.split("/").pop();
},

最后你的计算函数应该返回一个字符串而不是一个数组

computeURL: function(userId) {
  return 'http://api.dev/user/' + userId;

虽然您确实需要将完整的域名放在网址中,但它是否只是相对于应用程序的其余部分来自同一个域?

this.userId的设置会自动使计算的网址