从Javascript访问聚合物函数

时间:2017-01-25 19:40:25

标签: javascript socket.io polymer polymer-1.0

很抱歉造成的不便(我的英语不是很好,我正在使用翻译来写这个)。 我已经搜索了StackOverFlow和其他网站,我找不到我需要的答案。 我正在使用Polymer开发一个项目,我在其中声明了如下函数:

Polymer({
  is: 'LaserLand-Cronometro',
  properties: {
    jugadores: Object,
    minuto: Number,
    segundo: Number,
    centesima: Number,
    hora:{
      type: String,
      value: '00:00:00'
    },
    task: Number
  },
  cronometro: function(){
    this.centesima++
    if(centesima>99){
      this.centesima=0
      this.segundo++
    }else if(segundo > 59){
      this.segundo=0
      this.minuto++
    }
    let mm;
    let ss;
    let cc;
    if(this.centesima<9){cc='0'+this.centesima}
    if(this.segundo<9){ss='0'+this.centesima}
    if(this.minuto<9){mm='0'+this.minuto}
    this.hora=mm+':'+ss+':'+cc
  },
  evento: function(e){
    console.log(e);
  }
});

但是当我使用Socket.io时,我需要使用javascript vanilla访问它们,例如:

<script>
Polymer({
  is: 'LaserLand-Cronometro',
  properties: {
    jugadores: Object,
    minuto: Number,
    segundo: Number,
    centesima: Number,
    hora:{
      type: String,
      value: '00:00:00'
    },
    task: Number
  },
  cronometro: function(){
    this.centesima++
    if(centesima>99){
      this.centesima=0
      this.segundo++
    }else if(segundo > 59){
      this.segundo=0
      this.minuto++
    }
    let mm;
    let ss;
    let cc;
    if(this.centesima<9){cc='0'+this.centesima}
    if(this.segundo<9){ss='0'+this.centesima}
    if(this.minuto<9){mm='0'+this.minuto}
    this.hora=mm+':'+ss+':'+cc
  },
  evento: function(e){
    console.log(e);
  }
});
var socket = io('http://localhost:7000',{'forceNew': true});
var time;
socket.on('inicio', function(data){
    time = setInterval(cronometro, 100);
});

我已经尝试过不同的方法,但没有人走路,所以我需要你的帮助。 换句话说,有没有办法直接从javascript访问聚合物中声明的函数?

1 个答案:

答案 0 :(得分:3)

您无法调用此方法,因为尚未创建实例!

您的代码似乎已经定义了一个名为“LaserLand-Cronometro”的自定义元素。您的方法cronometro仅在此自定义元素的实例中可用。 所以你要做的就是首先创建/获取自定义元素的实例,然后调用它的方法。

您必须在Polymer registration life cycle中包含Socket.io或自己创建一个实例。

....
var laserLand = document.createElement('LaserLand-Cronometro');

var socket = io('http://localhost:7000',{'forceNew': true});
var time;
socket.on('inicio', function(data){
    time = setInterval(laserLand.cronometro, 100);
});

我可能会建议创建一个自定义元素,它通过socket.io封装你的后端连接,并提供一个API,将数据绑定到你的聚合物应用程序中。 也许firebase elements给了一些灵感。

希望这有帮助。

相关问题