jeudi 26 mars 2015

Knockoutjs - Template with dynamic variables


I'm learning javascript and ko by trying my hand at a character sheet for my favorite tabletop rpg. Since this is day 3, I'm not even sure I'm approaching this correctly, but below is my attempt at producing a form for skills. It produces no errors, but also has zero functionality.


The evals are my attempt to produce a reference to other observables/computed observables, but no luck. The $data part of the eval was a later addition of an interpretation of advice on how to correct the problem.



<script type="text/html" id="skills-template">
<div data-bind="template: { name: 'skills-template', foreach: skills }"></div>
<div class="row">
<div class="col-md-1" data-bind="text: skill"></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skill + 'Total')"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Ranks')" /></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skillMod)"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Mod')" /></div>
<div class="col-md-1"><strong data-bind="text: untrained"></strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-4">&nbsp;</div>
</div>

</script>


For reference, here is the skills obj I created.



self.skills = [
{ skill: 'Acrobatics', skillMod: 'dexMod', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Appraise', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Bluff', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Climb', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Craft', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Diplomacy', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' }
]


And this is an example of a computed observable I tried.



self.AcrobaticsTotal = ko.computed(function() {
return Number(self.AcrobaticsRanks()) + Number(self.dexMod()) + Number(self.AcrobaticsMod()) + Number(self.AcrobaticsTrained());
}, this);


I can get this all working if I hand code it, but I thought I would do it smartly and avoid typing all 40 skills and all of the associated observables. Thanks for any advice.


edit: I should have been more clear, I'm trying to get the data-bind to be the equivalent of other observables that I've declared. I want eval($data.' + skill + 'Total') to be acrobaticsTotal and have ko act on the acrobaticsTotal observable.





Aucun commentaire:

Enregistrer un commentaire