2017-05-24 21 views
1

我在Meteor.js的Blaze模板上遇到了一個奇怪的問題。以下模板呈現四倍(具有{{#each}}操作者)在流星上使用ReactiveVar時等待Blaze的數據

<template name="circle"> 
    <div class="col-md-6"> 
    <div class="circle-container"> 
     <div class="circle {{option}}" style="border: 9px solid {{color}}"> 
     <div class="circle-text {{option}}" style="color:{{color}}">{{name}}</div> 
     </div> 
    </div> 
    </div> 
</template> 

的數據被傳遞給模板作爲保持對象的陣列的ReactiveVar。每個對象在模板上呈現一個圓圈。產生這種數據的邏輯坐在下面:

const colorSet = ['red','gold','blue','green','orange','turquoise','wheat','fuchsia','purple']; 
const colorNames = ['VERMELHO','AMARELO','AZUL','VERDE','LARANJA','TURQUESA','BEGE','ROSA','ROXO']; 

var limit = colorSet.length; 

// helper functions 
function getRandomPosition() { 
    return Math.floor(Math.random() * (limit + 1)); 
} 

function getRightColor() { 
    let position = getRandomPosition(); 
    let rightColor = { 
    color: colorSet[position], 
    name: colorNames[position], 
    right: 'right-option', 
    }; 
    return rightColor; 
} 

function getWrongColor() { 
    let position1 = getRandomPosition(); 
    let position2 = getRandomPosition(); 
    while (position1 === position2) { 
    position2 = getRandomPosition(); 
    } 
    let wrongColor = { 
    color: colorSet[position1], 
    name: colorNames[position2] 
    }; 
    return wrongColor; 
} 

function make4Circles() { 
    let circles = []; 
    circles.push(getRightColor()); 

    for (let i = 0; i < 3; i++) { 
    circles.push(getWrongColor()); 
    } 
    console.log('circles:', circles) 
    return circles 
} 

//// 
// TEMPLATE HELPERS 
/// 
Template.gameArea.onCreated(function() { 
    this.circleArray = new ReactiveVar(make4Circles()); 
}) 


Template.gameArea.helpers({ 
    circles() => { 
    return Template.instance().circleArray.get(); 
    } 
}) 

的問題是,頁面有時缺乏數據,是什麼給我的印象是之前的數據準備就緒模板被渲染。由於火焰是反應性的,我認爲這是不會發生的,因爲跟蹤器會知道數據已經改變並且會重新渲染模板。但事實是,有時它缺少一些數據。

我期待所有的文件過來,我不知道如果我面臨着某種錯誤或做錯事的......

如果有人想運行的代碼,它是在這個GitHub庫:https://github.com/kemelzaidan

回答

1

我懷疑問題不是來自Blaze,而是來自您的數據生成算法。

您的console.log('circles:', circles)是否始終輸出正確的數據?

Math.floor(Math.random() * (limit + 1))似乎有時會產生一個整數你的數組索引範圍。

在你的情況,limit將是9(在你的colorSet陣列,因此其具有從0到8個索引即9項),所以limit + 1是10

然後Math.floorMath.random() * 10有時會得到9,其超出了你的數組範圍。

=>只是刪除那+1應該解決您的問題。

+0

Thanks @ghybs!這樣一個愚蠢的錯誤......但有時當我們單獨做事情時,我們不能發現這樣一個簡單的小錯誤。 – kemelzaidan