2016-08-22 2 views
0

Прежде всего, извините меня за мой английский, я французский.Сохраните значение переменной для каждой функции JavaScript, twig, JointJS

Я прихожу к вам, потому что у меня проблема. У меня есть функция «drop», петля твига, которая извлекает имена полей, и я бы сгенерировал первую переменную с циклом (var = color_fieldName #color) и сохранял значение этой переменной каждый раз, когда мы повторяли эту функцию. В моем коде, цвет меняется каждый раз:

function drop(ev, id, x, y) { //We drop the item 

      {% for element in listElement %} 
       if ({{ element.id }} == id) 
       { 
        //We created a variable with a random color to each tag 

        {% for field in element.fields %} 
         {% if (field.valueType == "tag") and (field.valueBool == 1) %} 
     /*THIS VARIABLE ==>*/ var color_{{field.name|replace({' ': ''})}}; 
          var color = Colors.random(); 
          color_{{field.name|replace({' ': ''})}} = color.rgb;** 
         {% endif %} 
        {% endfor %} 

        //Generation of legend for tag 
        {% set posLeg = 20 %} 
         {% for field in element.fields %} 
          {% if (field.valueType == "tag") and (field.valueBool == 1) %} 
           if(legend{{field.name|replace({' ': ''})}} == null){ 
            var fiedName = '{{field.name}}' 
            var legend{{field.name|replace({' ': ''})}} = new joint.shapes.basic.Rect({ 
             markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/><circle class="legend_{{element.name|replace({' ': ''})}}_{{field.name|replace({' ': ''})}}"/></g>', 
             position: {x: {{posLeg}} , y: height-30}, 
             size: { width: (fiedName.length * 8)+20, height: 30 }, 
             attrs: { 
               rect: { fill: 'white', stroke: 'none'}, 
               '.legend_{{element.name|replace({' ': ''})}}_{{field.name|replace({' ': ''})}}': { 
                r: 7, 
                cx: 0, 
                cy: 15, 
                fill : color_{{field.name|replace({' ': ''})}}, 
                stroke: 'black' 
               },                
               text: { 
                text : '{{field.name}}', 
                fill : 'black' 
               } 
              }, 
            }); 
           } 
           graph.addCell(legend{{field.name|replace({' ': ''})}}); 
           {% set posLeg = posLeg + 120 %} 
          {% endif %} 
         {% endfor %} 

        lastDropped = id; 

        {% set posCy = 0 %} 
        var E{{ element.name|replace({' ': ''}) }} = new joint.shapes.basic.Image({ 
         markup: '<g class="rotatable"><g class="scalable"><rect/></g><image/><text/>}{% for field in element.fields %}{% if (field.valueType == "tag") and (field.valueBool == 1) %}<circle class="{{element.name|replace({' ': ''})}}_{{field.name|replace({' ': ''})}}"/>{% endif %}{% endfor %}</g>', 
         position: {x: x, y: y}, 
         size: {width: 100, height: 50}, 
         attrs: { 
          image: { 
           {% if element.imageName %} 
           "xlink:href": "{{ asset('uploads/documents/'~element.imageName) }}", 
           {% else %} 
           "xlink:href": "{{ asset('/bundles/diagram/img/p.png') }}", 
           {% endif %} 
           width: 100, height: 50 
          }, 
          text: { 
           text: '{{ element.name }}', 
           fill: 'black', 
          }, 
          {% for field in element.fields %} 
           {% if (field.valueType == "tag") and (field.valueBool == 1) %} 
            '.{{element.name|replace({' ': ''})}}_{{field.name|replace({' ': ''})}}': { 
             r: 7, 
             cx: 90, 
             cy: {{posCy}},              
             fill : color_{{field.name|replace({' ': ''})}}, 
             stroke: 'black' 
            }, 
           {% set posCy = posCy + 15 %}                
           {% endif %} 
          {% endfor %} 
          idElem: '{{ element.id }}', 
         } 
        }); 
        graph.addCell(E{{ element.name|replace({' ': ''}) }}); 
       } 
      {% endfor %} 

    } 

Для получения дополнительной информации, я нахожусь под Symfony 3, я использую библиотеку JOINTJS для диаграмм и JavaScript

Спасибо заранее!

+0

плохая практика для создания Javascript кода PHP. – Alsatian

+0

Как долго вы хотите сохранить свою переменную? Страница? Сессия? 1 месяц ? – Alsatian

+0

То есть? – Lucatorze

ответ

0

Создание объекта в Gobal объеме, в котором хранятся значения:

var colorsDictionary = {}; 

function getColor(tag){ 
    if(tag in colorsDictionary){ 
     return colorsDictionary[tag]; 
    } 
    else{ 
     colorsDictionary[tag] = Colors.random().rgb(); 
     return colorsDictionary[tag]; 
    } 
} 
Смежные вопросы