用于功能模块化的聚合物脚本专用组件

Polymer script only component for function modularization

本文关键字:脚本 专用 组件 聚合物 功能 功能模块 模块化 用于      更新时间:2023-09-26

我可以在Polymer中使用仅脚本组件来保存跨应用程序使用的所有帮助程序函数吗?我不确定拥有可重用functions的推荐方法是什么,constants可以跨组件导入?

<dom-module id="helper-functions">  
  <script>
    (function() {
        var helper1 = function() { ... };
        var helper2 = function() { ... };
        Polymer({
            is : 'helper-functions' 
        });
    })();
  </script>
</dom-module>

你"可以"这样做,但这取决于这些帮助程序函数在做什么以及它们是否需要任何"聚合物"功能。

将这种事情包装成一种"行为",似乎是聚合物元素本身做事的方式。 将帮助程序拆分为多个功能区域,使每个区域成为单独的行为,然后将行为包含在需要它的元素中。下面是一个示例来展示它是如何完成的(我将我的所有行为都包含在 PAS 命名空间中。

<link rel="import" href="../polymer/polymer.html">
<script>
window.PAS = window.PAS || {};
(function() {
  'use strict';
  var dialogs = [];
  PAS.DialogBehaviour = {
    attached: function() {
      dialogs.push(this);  //Capture all dialogs as they start up
    },
    _requestClose: function() {
      this.async(function() { //Wait a second to allow inflight ajax to have a chance to finish
        dialogs.forEach(function(dialog) {
          if (dialog !== this) {
            dialog._forceClose();
          }
        },this);
      },1000);
    },
    _forceClose: function() {
      //abstract
    }
  };
})();
</script>

然后我把它包含在我的元素中,比如...

Polymer({
  is: 'pas-standin',
  behaviors: [AKC.Route,PAS.DialogBehaviour,Polymer.NeonAnimatableBehavior],
  listeners: {
    'pas-error': '_closeDialog'
  },

但是对于纯 javascript 函数,我已经在我的应用程序.js文件中添加了我的辅助函数。我目前没有那么多,我怀疑如果我这样做了,那将表明我没有设计正确的元素。