Chris Frank
Chris Frank

Reputation: 4452

Creating a simple backbone app

I am trying to teach myself Backbone.js by converting my simple static web app to a one page Backbone app. My problem is I can't find a simple tutorial for my problem.

I have the following function:

function convert(ins) {
    var numbers = parseFloat(ins);
    //Test for NAN
    if(isNAN(numbers)){
        $("#output").html("Error");
    }else{
        var conver = (numbers * 12);
        $("#output").html(conver);
    }
}

Right now this function gets called when the user inputs data into a field. It updates the output div automatically. I want to have lots of conversion "apps". And the convert function needs to update when a user visits the page. How should I go about making models for each of my pages? The only line I want to change in my convert function is:

var conver = (numbers * 12);

I am really new to backbone obviously, and this is the last problem I need solved before I can start re-working my sites code.

I would really appreciate any help. Thanks!

Upvotes: 2

Views: 347

Answers (2)

Jack
Jack

Reputation: 10993

Since from the code you posted it seems like all that is happening is some conversions based on some user interactions, it would seem that a plain view without a backing model would suffice. If your conversion function depended on some specific data (for example some formulas that came from your server) then perhaps a model would be warranted, but based on what you posted I don't really see the need.

For example say your markup was something like the following

  <div id="divConversionCalc">
    <label for="txtInputNum">Enter inches</label> <input type="number" id="txtInches" />
    <label>Feet</label> <div id="dvOutput"></div>

  </div>

You can declare a backbone.js view that would encapsulate your function like the following

    var ConversionView = Backbone.View.extend({
        el: '#divConversionCalc',

        events: {
            "change #txtInches": "convert"
        },

        convert: function (e) {
            var numbers = parseFloat(this.$el.find('#txtInches').val());
            if (isNaN(numbers)) {
                this.$el.find("#dvOutput").html("Error");
            } else {
                var conver = (numbers * 12);
                this.$el.find("#dvOutput").html(conver);
            }

        }

    });

    $(function () {
        new ConversionView();
    });

JSBin

Upvotes: 2

Mark Rushakoff
Mark Rushakoff

Reputation: 258188

Without seeing the rest of your code, it looks like your problem is that ins is a string, and you can't multiply a string with a number in Javascript. You'll probably be good to go if you change it to numbers * 12 instead.

Upvotes: 0

Related Questions