【发布时间】:2015-12-10 19:29:25
【问题描述】:
问题:
我想尝试在我的 Firebase 的根目录下运行多个游戏,它们都有 Firebase 生成的 id,
当我尝试使用<firebase-collection> 获取它们时,我总是得到一个对象数组,并且使用 Polymer 进行双向绑定非常困难。
有没有办法将 Firebase 数据作为对象获取?
我尝试添加data-as-object 属性,但没有成功,我还得到了一个数组。
我什至尝试通过简单地将表单 <-collection> 更改为 <-document> 来使用 <firebase-document> 元素,但随后更新游戏数据并没有推送到 firebase。
我不知道这是否可能......
或者有没有一种很好的双向绑定方法?
我无法使用数组项的索引,例如:this.set('gameData.' + i),因为当我尝试修改数组中 Object 下的值时,我收到错误 Uncaught Error: unexpected key 2
Github上的完整代码
我的代码:
数据提供者:
<firebase-collection location="https://***.firebaseio.com"
data="{{data}}" data-as-object log>
</firebase-collection>
<!-- script -->
Polymer({
is: 'tmp-game-data',
properties: {
data: {
notify: true
}
}
});
游戏元素:
<!-- map with several players(Array), -->
<!-- an player(Object) has some properties -->
<!-- on-map-ready, when the map is fully configured -->
<tmp-map players="{{game.players}}"
on-map-ready="_mapReadyCallback">
</tmp-map>
<!-- menu user for creating and -->
<!-- joining games with selected settings -->
<tmp-menu on-start-global-game="startGlobalGame"
on-join-game="joinGame">
</tmp-menu>
<tmp-game-data data="{{gamesData}}"></tmp-game-data>
<!-- script -->
var blocks = []; //Map blocks, global access
Polymer({
is: 'tmp-game',
properties: {
gamesData: {
notify: true
},
game: {
notify: true
},
gameId: {
type: String
}
},
startGlobalGame: function(e) {
var gameId = getRandomString(6);
this.set('gameId', gameId);
var player = {id: /*playerId*/};
var players = [player];
this.push('gamesData', {
gameId: gameId,
maxPlayers: e.detail.maxPlayers,
players: players
});
this.selectGame();
//generate map
},
joinGame: function(e) {
var gameId = e.detail.gameId;
for (var i = 0; i < this.gamesData.length; i++) {
if(this.gamesData[i].gameId === gameId) {
var map = this.get('gamesData.' + i + '.map');
//generate map with the map of the game
}
}
this.selectGame();
},
selectGame: function() {
for (var i = 0; i < this.gamesData.length; i++) {
if(this.gamesData[i].gameId === this.gameId) {
this.set('game', this.gamesData[i]);
this.linkPaths('game', 'gamesData.' + i);
}
}
},
_mapReadyCallback: function(e) {
for (var i = 0; i < this.gamesData.length; i++) {
if(this.gamesData[i].gameId === this.gameId) {
//get the map as a json
var map = JSON.stringify(blocks);
this.set('gamesData.' + i + '.map', map);
}
}
}
});
【问题讨论】:
-
我删除了
<dom-module>、<template>和<script>以简化代码
标签: arrays firebase polymer 2-way-object-databinding