使用Backbone的嵌套属性的模板

时间:2012-07-10 13:22:36

标签: backbone.js backbone-relational

我有一个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-5555更改为555-555-1234,但JSON对象中的client对象的电话号码保持不变。我需要以某种方式更改该电话号码。

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

2 个答案:

答案 0 :(得分: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);            
}
});

参考: Can I bind form inputs to models in Backbone.js without manually tracking blur events?

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

    model.on('change:client_phone', 
       function () { 
           //Set client value here  
       });

答案 1 :(得分: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
    )