2017-01-25 37 views
0

对不起,造成了不便(我的英文不太好,我正在用翻译来写)。 我已经搜索了足够的在StackOverFlow和其他网站看,我没有找到我需要的答案。 我的工作与聚合物的一个项目,在我所宣称的功能如下:从Javascript访问高分子功能

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香草来访问它们,例如:

<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访问聚合物中声明的函数?

回答

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给一些启发。

希望这会有所帮助。