2017-01-30 20 views
0

我有一个聚合物应用程序需要输入文本(ID),并根据ID是否在列表中返回“是”或“否”。理想情况下,用户可以按回车或点击“查找”按钮,“搜索ID”功能将被调用。如何在提交聚合物纸张输入时调用函数?

我可以不使用表单吗? 如果我使用表单,我可以在不发出post/put/get请求的情况下执行此操作吗?数据全部存储在元素的属性(数组)中。

<dom-module id="demo-app"> 
    <template> 
    <style> 
     :host { 
     display: block; 
     } 
    </style> 
    <paper-card heading="Search for ID"> 
     <div class="card-content"> 
     <paper-input id="input" always-float-label label="ID"</paper-input> 
     </div> 
    </paper-card> 
    </template> 

    <script> 
    Polymer({ 

     is: 'demo-app', 

     properties: { 
     myIds: { 
      type: Array, 
      value: ['testID1', 'testID2'], 
     }, 
     inputObj: { 
      type: Object, 
      value: function(){ 
      return this.$.input; 
      } 
     }, 
     userInput: { 
      type: String, 
     }, 
     }, 
     onEnter: function(){ 
     if(this.myIds.includes(this.userInput)) { 
      console.log(this.userInput); 
     } 
     }, 

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

您可以更新您的问题,以便它显示[最小,完整和可验证的示例]中的所有相关代码(http://stackoverflow.com/help/mcve)。 –

+0

我见过类似的问题和相关的答案 - 比如1)使用iron-a11y-key来监听keys =“enter”和2)制作一个名为“checkForEnter”的函数,如if(e.keyCode === 13)并在纸张输入元素属性上添加on-keydown =“checkForEnter”。甚至有些地方我使用表单并覆盖默认表单提交。想知道是否有“最佳实践”的方式来做到这一点 –

回答

1

高分子最好的做法是“使用平台”,在这种情况下HTML(一个按钮的默认行为是提交表单)&一小段JavaScript会工作。

具体来说,包你输入的形式,并添加一个按钮:

<form id="demoAppForm"> 
    <paper-card heading="Search for ID"> 
    <div class="card-content"> 
     <paper-input id="input" always-float-label label="ID"</paper-input> 
    </div> 
    <button>Lookup</button> 
    </paper-card> 
<form> 

然后设置一个事件监听器当表单提交,preventDefault该事件(所以它不会做GET请求),并通过将这些功能,您Polymer({...})呼叫你想用什么数据:

attached: function() { 
    this.listen(this.$.demoAppForm, 'submit', 'onSubmit'); 
}, 

onSubmit: function(event) { 
    event.preventDefault(); 
    console.log('Lookup this:', this.$.input.value); 
}, 

请确保您删除事件侦听器也当元件脱离:

detached: function() { 
    this.unlisten(this.$.demoAppForm, 'submit', 'onSubmit'); 
}, 
+0

我可以简单地通过添加一个on-change =“inputHandler”来实现它 - 由于某些原因,只有当我按下Enter时才会触发它。如果我将任何东西绑定到值,例如

{{userInput}}被输入

该值将实时更新 - 但该函数仅在我按Enter时运行。我也将值设置为“value =”{{userInput :: input}}“,尽管我不确定”:: input“部分是什么 - 你知道吗? 无论如何我会使用你的代码,谢谢你的向我展示这是如何完成的! –

相关问题