1

我有一个Appointment模型,它的每个实例都有一个Client. 这是我编辑约会的模板:

<form id="edit-appointment" name="appointment" class="mobile_friendly">
  <div class="field">
    <input type="text" name="start_time_ymd" id="start_time_ymd" value="<%= start_time_ymd %>" placeholder="Start Date">
    <input type="text" name="start_time_time" id="start_time_time" value="<%= start_time_time %>" placeholder="Start Time">
  </div>

  <div class="field">
    <input type="text" name="client_name" id="client_name" value="<%= client.name %>" placeholder="Client">
    <input type="hidden" name="client_id" id="client_id" value="<%= client.id %>" placeholder="Client ID">
  </div>

  <div class="field">
    <input type="text" name="client_phone" id="client_phone" value="<%= client.phone %>" placeholder="Phone">
  </div>

  <div class="field">
    <input type="text" name="notes" id="notes" value="<%= notes %>" placeholder="Notes">
  </div>

  <div class="actions">
    <input type="submit" value="Update Appointment" />
  </div>

</form>

<a href="#/index/<%= stylist_id %>">Back</a>

我的问题是我的Client属性没有正确传递给服务器。保存时传递给服务器的 JSON 对象如下所示。假设我有一个客户的电话号码555-555-5555,但我将其更改为555-555-1234然后提交表单:

{"appointment":
  {"start_time_ymd":"1/1/2000",
   "client_phone":"555-555-1234",
   "client":{"phone":"555-555-5555"}}

我省略了很多不相关的字段,但希望你明白我的意思。我已从 更改client_phone555-555-5555555-555-1234clientJSON 对象中的对象的电话号码未更改。我需要以某种方式更改该电话号码。

如何使这些字段(例如电话号码字段)实际“接受”,以便它们作为client对象的一部分appointment而不是直接在下面传递给服务器appointment?我正在使用 Backbone-relational,如果这有所作为的话。

4

2 回答 2

2

如果您更改表单文本后您的模型没有更新,那么您需要明确更新数据

SampleView = Backbone.View.extend({
el: '#formEl',
events : {
    "change input" :"changed",
    "change select" :"changed"
},

initialize: function () {
    _.bindAll(this, "changed");
},
changed:function(evt) {
   var changed = evt.currentTarget;
   var value = $("#"+changed.id).val();
   var obj = "{\""+changed.id +"\":\""+value+"\"";

   // Add Logic to change the client phone
   if (changed.id === 'client_phone') {
          obj = obj + "client\":{\"phone\":\""+value+"\""};
   }
   obj = obj + "}";
   var objInst = JSON.parse(obj);
   this.model.set(objInst);            
}
});

参考: 我可以在不手动跟踪模糊事件的情况下将表单输入绑定到 Backbone.js 中的模型吗?

您还可以绑定到模型更改事件

    model.on('change:client_phone', 
       function () { 
           //Set client value here  
       });
于 2012-07-11T05:27:49.513 回答
1

我能够让它像这样工作:

class Snip.Views.Appointments.EditView extends Backbone.View
  template : JST["backbone/templates/appointments/edit"]

  events :
    "submit #edit-appointment" : "update"

  update : (e) ->
    e.preventDefault()
    e.stopPropagation()

    # THE ONLY CHANGE I MADE WAS TO ADD THIS LINE
    @model.attributes.client.phone = $("#client_phone").val()

    @model.save(null,
      success : (appointment) =>
        @model = appointment
        window.location.hash = "/#index/" + @model.attributes.stylist_id
    )   
于 2012-07-19T17:28:52.263 回答