1

我正在尝试了解 Backbone.js 及其工作原理。我创建了两个接受任何值的文本框,单击按钮(Multipy)时,值显示在下面的框中,这可行,但我希望将两个值的乘法显示在第三个框中 - 我试图分配两者值到变量并相乘,但它似乎不起作用。我认为文本框的返回值存在一些问题,认为它是 NAN。无论如何,请看看并提出建议。我已经注释掉了不起作用的代码。直播网址:http ://egoless.co.uk/learning/learn_backbone/first-backbone-app.php

  <!DOCTYPE html>
  <html>
    <head>
    <title>Testing</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="underscore.js">
  </script><script type="text/javascript" src="backbone.js"></script>
  <style>
  .size {
    width: 100px;
    height: 30px;
    border: solid 1px red;
    float: left;
    margin-left: 10px;
    text-align: center;
    font-weight: bold;
  }
  </style>
    </head>
    <body>
    <input type="text" id="box1" />
  &nbsp;
  <input type="text" id="box2" />
  &nbsp;
  <button id="myBtn">Multiply</button>
  <br>
  <br>
  <div id="myBox" class="size"></div>
  <div id="myBox2" class="size"></div>
  <div id="myBox3" class="size"></div>

  <script>

  (function($){
  //defining model 1
    PersonModel1 = Backbone.Model.extend({

      defaults:{
              age : function(){

               return  $("input#box1").val();

              }
          }
    });

    myPerson1 = new PersonModel1();

    //defining model 2
    PersonModel2 = Backbone.Model.extend({

      defaults:{
              age : function(){

               return $("input#box2").val();

              }
      }
    });

    myPerson2 = new PersonModel2();

    //defining collection


    Group = Backbone.Collection.extend({
          Model: PersonModel1,
          Model: PersonModel2,
          url:"#"

      })

          People = new Group([]);
          People.add(myPerson1);
          People.add(myPerson2);  

    //adding view

    ResultView = Backbone.View.extend({
          el:'button',
          events:{
              'click':'render'
          },
        render:function(){

          val1 = myPerson1.get('age');
          val2 = myPerson2.get('age')
          val3 = val1*val2 // not working
          $('div#myBox').html(val1);
          $('div#myBox2').html(val2);
          $('div#myBox3').html(val3); // not working
          $('input#box1').val("");
          $('input#box2').val("");
          return this;
          }
      })




    $(document).ready(function(e) {
       myResultView = new ResultView();
    });

  })(jQuery);

  </script>
  </body>
  </html>
4

1 回答 1

0

在模型定义的默认部分中,您只能为属性分配值。要返回值年龄,您应该编写单独的函数。

          defaults:{},
          age : function(){
           return  $("input#box1").val();
          }

你可以这样打电话

      val1 = myPerson1.age();
      val2 = myPerson2.age();
      val3 = val1*val2 ;
于 2013-01-24T19:03:34.637 回答