HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

HTML/Attrs Tester Environment

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
attrshtmltesterenvironment

Problem

I have a few objectives (which are working fine, but I want tips in case I can improve it).

Let me try to make this as clear as possible, as this is a much larger project:

There are three move categories:

  • Hammer (10 damage)



  • Scythe (5 damage)



  • Meditate (0 damage)



I will be having hundreds of additions, but these values above are static indefinitely. I'm trying to update a total damage count, but the kicker is that the player can change this move type in the middle of adding other things.

Essentially, I need it to display an accurate estimated damage count based on other values that will end up occurring (this is entirely GUI based, I have the back-end data working).

HTML:


Hammer (10)

Scythe (5)

Meditate (0)

Total
0


JS:

$(function() {
    var dom = $('#total');
    var total = 0;
    var moveVal = 0;
    $('#addDmg').on('click', function() {
        total += 1;
        dom.text(total + moveVal);
    });
    $('#remDmg').on('click', function() {
        total -= 1;
        dom.text(total + moveVal);
    });
    $(':radio').on('click', function() {
        moveVal = $(this).data('damage');
        dom.text(total + moveVal);
    });
});


3 questions:

  • I'm using data-attr via HTML to find the values. I understand it would be quicker to run this in an array or something, but if it has to traverse the DOM anyway to find out which one was selected, is there any real performance upgrade opposed to using data in HTML?



  • If these are the only radio buttons on the page, is the way I've built my :radio click function reasonable? Welcoming any tips you could provide if somebody else has advice to make this faster.



  • Is using a variable for moveVal pretty much the only way to tackle this without adding all the other additions and whatnot EVERY time?



Maybe this will make more sense if I show a full demo?

Play: Js Fiddle: http://jsfiddle.net/epZzP/

Solution

Ahh, the origins of a simulator. I have always wanted to create one of those. Anyways...

I suggest you model this all in the JS. If you follow MVC, then all data (or most of it) live in the Model, the data storage. The View would be the HTML, and all event handlers like clicks, change, hovers, live in the controller. Controller updates the model data, like add/remove damage and the view updates values when the model data changes.

Using MVC, or a derivative, allows separation of concerns. For instance, you can easily swap HTML and avoid breaking the logic that controls actions and calculations.

Context

StackExchange Code Review Q#47192, answer score: 3

Revisions (0)

No revisions yet.