【问题标题】:Backbone js Model/View setup主干 js 模型/视图设置
【发布时间】:2016-02-24 01:47:33
【问题描述】:

我正在尝试以纯粹的方式构建应用程序。这是设置模型和渲染视图的正确方法吗?

最新的小提琴 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();

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    您已经很好地设置了模型和视图之间的关系。我要说的一件事是,您很快就会厌倦以自己的方式进行模板化:

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

    在您的标记中,然后在您的视图中选择一个 DOM 对象并在您的渲染函数中设置 html:

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

    以这种方式构建应用程序会很困难。您可能想开始使用一些客户端模板来简化您的生活。小胡子之类的东西。一旦您使用许多键模板化模型或模板化模型列表,这将开始有用。这是一篇文章,展示了一个带有主干的示例:https://gist.github.com/kyleondata/3440492

    【讨论】:

    • 我明白了 - 所以给它加点小胡子。我的下一步将是 - 向其中添加一些其他模型/视图 - 并将其作为一个更大的应用程序的一部分工作。这是最新的代码。我试图确保正确设置模型/视图以使其成为纯主干 js 应用程序 -- jsfiddle.net/g48ckukd/6
    【解决方案2】:

    好的,谢谢你们的帮助。

    我已将此起始结构放入我的完整应用程序中。我不得不关闭 ajax,因为那里的服务器似乎已经停止响应。

    您能否检查一下这个应用程序 - 告诉我是否需要将某些内容放入集合中或以不同的方式命名等等。

    //最新的小提琴 https://jsfiddle.net/g48ckukd/31/

    用户银行模型和用户银行视图

      //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);
        }
      });
    

    比特币模型和比特币视图

      //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);
        }
      });
    

    应用程序本身包含上述内容并形成事件

      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();
    

    【讨论】:

    • 此外,木偶即将到来——我将如何开始调整上面的代码以合并它? marionettejs.com/docs/v2.4.4/marionette.application.html
    • MyApp.addRegions({ someRegion: "#some-div", anotherRegion: "#another-div" }); -- 所以这就是把所有的选择器放在一个地方?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    相关资源
    最近更新 更多