繁体   English   中英

从Javascript访问聚合物函数

[英]Accessing polymer functions from Javascript

造成您的不便,敬请见谅(我的英语不太好,我正在用翻译器写这篇文章)。 我已经在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访问聚合物中声明的函数吗?

您无法调用此方法,因为还没有创建实例!

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

您必须在Polymer 注册生命周期中包含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,以将数据绑定到您的Polymer应用程序中。 也许火力基地的元素给了一些启发。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM