2014-04-01 1 views
9

Sto cercando di rendere un elemento di selezione con le opzioni, come questomanubrio: condizionalmente Aggiungi attributo

<select dropdown multiple class="dropdown" name="color"> 
     {{#each colors}} 
      <option value="{{value}}" {{isSelected parentColor id}}>{{title}}></option> 
     {{/each}} 
</select> 

Sto usando i seguenti manubrio aiutante

Handlebars.registerHelper('isSelected', function(input, color) { 
    return input === color ? 'selected' : ''; 
}); 

Il problema è che la selected l'attributo non appare su nessuno degli elementi option, ma quando inserisco uno console.log nell'helper del manubrio, vedo che uno corrisponde (input === color === true). Qualche idea su cosa faccio di sbagliato qui?

risposta

10

Questo è un esempio di funzionamento di quanto descritto,

http://jsfiddle.net/rtLGR/

hbs

<h1>Handlebars JS Example</h1> 
<script id="some-template" type="text/x-handlebars-template"> 

    <select dropdown multiple class="dropdown" name="color"> 
     {{#each colors}} 
      <option value="{{value}}" {{isSelected parentColor id}}>{{title}}</option> 
     {{/each}} 
</select> 
</script> 

js

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data = { 
    colors: [ 
     {id:1,value:1,title:"red",parentColor:2}, 
     {id:2,value:2,title:"green",parentColor:2}, 
     {id:3,value:3,title:"blue",parentColor:1} 
    ] 
}; 


Handlebars.registerHelper('isSelected', function (input, color) { 
    return input === color ? 'selected' : ''; 
}); 

$('body').append(template(data));