簡體   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