在Backbone中将数据从一个模型传递到另一个模型

时间:2013-11-17 01:11:57

标签: javascript jquery post backbone.js

<form>
  <input id = "one" class = "number">
  <input id = "two" class = "number">
  <input id = "three" class = "number">
  <input id = "four" class = "number">
</form>

在模型中。

我有一个按钮,它具有以下功能:

$("#button").click(function(){
  var mynumber = $("#one").val() + $("#two").val() + $("#three").val();
  //IF i do a this.model.save here it will POST all four fields that I dont want
});

问题:我想创建一个新模型,它获取此值mynumber并执行POST请求。到目前为止,我有这个:

var mymodel = Numbermodel.extend({
  this.model.set(mynumber);
  this.model.save({},{
    success: function(model, response) {
      console.log('success! ' + response);
    },
    error: function(model, response) {
      console.log('error! ' + response);
    }
  });
});

我不确定如何连接这两个。我只想发布mynumber而不是所有单独的字段。任何帮助将不胜感激?

1 个答案:

答案 0 :(得分:0)

var FormView = Backbone.View.extend({
      tagName: 'form',
      events: {
          'click #button': 'sentRequest'
      },
      initialize: function(){
         ...
      },
      render : function(){
         ...
      },
      sentRequest: function(){
          var mynumber = $("#one").val() + $("#two").val() + $("#three").val();
          var mymodel = new Numbermodel();
           model.set(mynumber);
           model.save({},{
              success: function(model, response) {
                  console.log('success! ' + response);
               },
              error: function(model, response) {
                  console.log('error! ' + response);
              }
          });
          return false;   //return false -- with the code form request does not send 
      }
})
$(function(){
    var view = FormView();
    view.render();

});

将该代码与您的html代码一起使用。