手动连接和断开绑定

时间:2013-05-14 20:47:04

标签: javascript ember.js

我正在创建一个包含结算和送货地址字段的表单。当用户检查“相同地址”时,我想在帐单地址和送货地址之间创建绑定;当取消选中该框时,我想断开该绑定。

HTML:

{{#with billingAddress}}
  {{view Ember.TextField valueBinding="firstName"}}
  {{view Ember.TextField valueBinding="lastName"}}
{{/with}}

{{view Ember.Checkbox checkedBinding="view.isSameAddress"}}

{{#with shippingAddress}}
  {{view Ember.TextField valueBinding="firstName"}}
  {{view Ember.TextField valueBinding="lastName"}}
{{/with}}

JavaScript的:

App.AddressesRoute = Ember.Route.extend({
  model: function() {
    return {
      billingAddress: Checkout.BillingAddress,
      shippingAddress: Checkout.ShippingAddress
    };
  }
});

App.AddressesView = Ember.View.extend({
  isSameAddress: false,
  useSameAddress: function() {
    if (this.isSameAddress) {
      // bind billing and shipping addresses
    } else {
      // remove binding
    }
  }.observes('isSameAddress')
});

App.Address = Ember.Object.extend({
  firstName: null,
  lastName: null
});

App.Billing = App.Address.create({
  firstName: 'John',
  lastName: 'Doe'
});

App.Shipping = App.Address.create({
  firstName: '',
  lastName: ''
});

我尝试过使用Ember.Binding以及其他一些没有运气的方法。我已经能够将发货设置为开票,但没有绑定,模板也不会更新。

对于正确方向的任何帮助或推动都将不胜感激!

1 个答案:

答案 0 :(得分:5)

我不是Ember专家,但似乎你需要使用Ember.Binding。也许是这样的:

Ember.oneWay(App.Shipping, "firstName", "App.Billing.firstName");

App.Shipping.firstNameApp.Billing.firstName字段之间设置单向绑定。

http://jsfiddle.net/mSxeP/1/