【发布时间】:2016-10-17 16:58:52
【问题描述】:
我有以下聚合物元素,它根据 pubnub 消息绘制一个简单的图表。它适用于“实时”数据 (.subscribe())。但是由于某种原因,当我使用执行完全相同的回调的 pubnub .history() 方法时,图表没有更新。快速调试告诉我图表元素 (dom-repeat) 在处理 ($.append) 历史数据时尚未呈现。我该如何解决这个问题?
聚合物模板:
<!-- Imports polymer -->
<link rel="import" href="../bower_components/polymer/polymer.html">
<!-- Defines element markup -->
<dom-module id="widget-horizon">
<template>
<strong id="widgetName">{{name}}</strong>
<template is="dom-repeat" items="{{charts}}">
<div id="chart{{index}}" class="horizon">
<span class="htitle">{{item.MessageBodyClassName}}</span>
<span class="hvalue">{{item.Value}}</span>
</div>
</template>
</template>
<script>
Polymer({
is: 'widget-horizon',
properties: {
dataid: {
type: String
},
name: {
type: String
},
gethistory: {
type: Number
},
charts: {
type: Array,
value: function() {return []}
},
isloading: {
type: Boolean,
value: true
}
},
ready: function() {
var self = this;
var color;
subscribe(self.dataid);
getHistory(self.dataid,self.gethistory);
registerCallback(this.dataid, function (data) {
self.charts = data.data;
for (var i = 0; i < self.charts.length; i ++){
var v = self.charts[i].Value;
if (v < .3) {
color = '#006837'
} else if(v >= .3 && v < 1) {
color = '#1a9850'
}
$('#chart' + i).append('<span class="hpip" style="background-color:' + color + '"></span>')
}
self.isloading = false;
});
}
});
</script>
</dom-module>
参考:
<widget-horizon dataid="RegResponseTimes" name="Response Times" gethistory="15"></widget-horizon>
getHistory()
function getHistory(dataid,count) {
pubnub.history({
channel : dataid,
callback : function(m){
var msgs = m[0];
if (count > msgs.length) count = msgs.length;
for (var i = 0; i < count; i++) {
var msg = msgs[i];
processMessage(msg);
}
},
count : count
});
}
processMessage()
function processMessage(msg){
callbackMapFunctions[msg.id](msg);
}
registerCallback()
function registerCallback(id, callback) {
callbackMapFunctions[id] = callback;
}
还有 subscribe(),它可以工作。
function subscribe(chnl) {
if(typeof pubnub != 'undefined') {
console.log("Subscribing to " + chnl);
pubnub.subscribe({
channel : chnl,
message : function(m){
var msg = $.parseJSON(m);
log(chnl,"Data Received");
processMessage(msg);
}
}
}
【问题讨论】:
-
调用
getHistory(self.dataid,self.gethistory)时,self.gethistory的值是多少?这是count参数的数字吗?不确定。 -
是的,在本例中是 15。
-
历史调用的输出是什么?完整的 JSON 有效负载响应
-
我看到的唯一区别是你的
subscribe这样做$.parseJSON(m);你发布的是 JSON 对象还是字符串化的 JSON?如果是后者,请只发布 JSON 对象。 -
这方面有进展吗?
标签: javascript jquery polymer polymer-1.0 pubnub