The Old County
The Old County

Reputation: 109

Backbone js Model/View setup

I am trying to build an application in a pure way. Is this a correct way of setting the model and rendering the view?

the latest fiddle https://jsfiddle.net/g48ckukd/19/

var UserBankModel = Backbone.Model.extend({
  defaults: {
    chips: 100
  },
  initialize: function() {
    console.log("UserBankModel initialize");
    this.on("change:chips", function(model) {
      var chips = model.get("chips"); // 23232
      console.log("Changed my chips to " + chips);
    });
  }
});


var UserBankView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html(userBankModel.get("chips"));
  }
});


//user bank model initialize with default 100 chips
var userBankModel = new UserBankModel();

//won or lost chips -- set new chip value
userBankModel.set({
  chips: 1001
});


var userBankView = new UserBankView({
  el: $("#bankvalue")
});
userBankView.render();

Upvotes: 0

Views: 193

Answers (2)

The Old County
The Old County

Reputation: 109

Ok guys, thank you for your help.

I've put this starting structure into my full application. I've had to turn off the ajax as the server there seems to have stopped responding.

Could you check over this application - tell me if I need to put something into a collection or call it differently etc..

//Latest fiddle https://jsfiddle.net/g48ckukd/31/

User bank model and user bank view

  //UserBankModel
  var UserBankModel = Backbone.Model.extend({
    defaults: {
      chips: 200
    },
    initialize: function() {
      console.log("UserBankModel initialize");
      this.on("change:chips", function(model) {
        var chips = model.get("chips"); // 23232
        console.log("Changed my chips to " + chips);
      });
    }
  });

  //UserBankView
  var UserBankView = Backbone.View.extend({
    initialize: function() {
     console.log("UserBankView initialize");
      this.render();
    },
    render: function(value) {
       this.$el.html(value);
    }
  });

a bit coin model and a bit coin view

  //BitcoinModel
  var BitcoinModel = Backbone.Model.extend({
    defaults: {
      currentValue: 0,
      lockedValue: 0
    },
    initialize: function() {
      console.log("BitcoinModel initialize");
      this.on("change:currentValue", function(model) {
        var currentValue = model.get("currentValue"); // 494
        console.log("Changed my currentValue to " + currentValue);
      });
    },
    getBitcoinValue: function(callback) {

      /*
        Backbone.ajax({
          dataType: 'json',
          url: "https://api.bitcoinaverage.com/ticker/USD",
          crossDomain: true,
          success: function(data) {
            callback(data);
          }
        });
      */

      json= {
        bid: 320,
        ask: 444
      };

      var mediumValue = (json.bid + json.ask) / 2;

      callback(mediumValue);
    }
  });

  //BitcoinView
  var BitcoinView = Backbone.View.extend({
    initialize: function() {
     console.log("BitcoinView initialize");
      this.render();
    },
    render: function(value) {
       this.$el.html(value);
    }
  });

the app itself that intwines the above and form events

  var App = Backbone.Model.extend({
    initialize: function() {
      var that = this;

      this.userBankModel = new UserBankModel();
      this.userBankView = new UserBankView({
        el: $("#bankvalue")
      });

      this.bitcoinModel = new BitcoinModel();
      this.bitcoinView = new BitcoinView({
        el: $("#bitvalue")
      });

      //setInterval(function() {
        //get val of bitcoin every second
        that.bitcoinModel.getBitcoinValue(function(mediumVal) {

          //set bit coin model
          that.bitcoinModel.set({
            currentValue: mediumVal
          });      

          //render the bit coin value
          that.bitcoinView.render(that.bitcoinModel.get("currentValue"));
        });
      //}, 1000);


      //render users chips
      this.userBankView.render(this.userBankModel.get("chips"));
    },
    currentBitcoinValue: 0,
    startBet: function(state) {
      console.log("start timer");
      this.state = state;

      //get locked value of bitcoin for the game

      var stashValue = this.bitcoinModel.get("currentValue");

      //set bit coin model with locked value
      this.bitcoinModel.set({
        lockedValue: stashValue
      });  

      var initialTimer = 5;

      var Timer = {
        i: initialTimer,
        onTimer: function() {
          var that = this;
          document.getElementById('timer').innerHTML = Timer.i;
          Timer.i--;
          if (Timer.i < 0) {
            app.gameResult();
            Timer.i = initialTimer; //reset
          } else {
            setTimeout(Timer.onTimer, 1000);
          }
        }
      };

      Timer.onTimer();
    },
    gameResult: function() {
      console.log("whats the result then");

      console.log("this.state", this.state);

      var lockedValue = this.bitcoinModel.get("lockedValue");
      var currentValue = this.bitcoinModel.get("currentValue");

      console.log("lockedValue>>", lockedValue);
      console.log("currentValue>>", currentValue);


      var result = "loss";//lose by default

      //locked value was higher
      if (
        this.lockedValue > this.currentValue && this.state["bet"] == "high" ||
        this.lockedValue < this.currentValue && this.state["bet"] == "low"
      ) {
        result = "win";//win if conditions are met
      }

      //get current value of user chips
      var newVal = this.userBankModel.get("chips");
      if (result == "win") {
        console.log("WIN -- you get chips");
        newVal += this.state["wager"];

      } else {
        console.log("LOSS -- you loose chips");
        newVal -= this.state["wager"];
      }

      //won or lost chips -- set new chip value
      this.userBankModel.set({
        chips: newVal
      });

      //render new user chips
      this.userBankView.render(this.userBankModel.get("chips"));
    }
  });





  var app = new App();

  var FormView = Backbone.View.extend({
    el: '#wager-form',
    events: {
      "submit": "doMethod"
    },
    doMethod: function(e) {

      e.preventDefault();

      var obj = [];
      this.$el.find('input[name]').each(function() {
          obj[this.name] = this.value;
      });

      //start bet
      app.startBet(obj);

    }
  });

  var form = new FormView();

Upvotes: 0

Robert Moskal
Robert Moskal

Reputation: 22553

You've set up the relationship between your model and your view fine. One thing I will say is that you are soon going to tire of templating the way you are:

bank value test <div id="bankvalue">2</div>

in your markup and then selecting a DOM object in your view and setting the html in your render function:

render: function() {
    this.$el.html(userBankModel.get("chips"));
}

It's going to be hard to build an application that way. You may want to start using some client side templating to simplify your life. Something like moustache. This will start being useful once your are templating a model with many keys, or templating a list of models. Here's an article that shows an example with backbone: https://gist.github.com/kyleondata/3440492

Upvotes: 2

Related Questions