1

我试图弄清楚如何编写pauseBinding()and resumeBinding(),以便我可以中断应用程序层之间的绑定,例如,如果用户输入到 Ember.TextField 时验证失败。

var source = Ember.Object.create({ value: 10 });
var target = Ember.Object.extend({ 
    source: source,
    valueBinding: 'source.value'
});

console.log(source.get('value'), target.get('value')); // 10, 10
target.set('value', 20);
console.log(source.get('value'), target.get('value')); // 20, 20

// Stop synchronizing between target.value and source.value
pauseBinding(target.get('valueBinding'));

// Only update target.value
target.set('value', 40);
console.log(source.get('value'), target.get('value')); // 20, 40

// Resume synchronizing, target.value is overwritten
resumeBinding(target.get('valueBinding'));

console.log(source.get('value'), target.get('value')); // 20, 20

或者,更一般地问这个问题:创建条件绑定最合适的习语是什么,绑定仅单向流动,仅另一向流动,双向流动或不流动取决于条件(另一个属性)?

条件可能是验证(如果验证失败,则不要进一步传播无效值),或者条件可能是响应 UI 状态(例如焦点)(如果控件已获得焦点,则不要以编程方式更新其值,如这会混淆 UI)。

例如,当一个带有 valueBinding 的 Ember.TextField 被聚焦时(如在活动用户输入中),我不希望它被更新,即使绑定的 to() 端更新。但这似乎是一个相反方向的 oneWay() 绑定(oneWay from -> to,而不是 oneWay to -> from)。

4

1 回答 1

-1

Here's a JSFiddle containing my best shot at creating a ConditionalBinding class:

http://jsfiddle.net/SDe8u/2/

You can use it like this:

var from = Ember.Object.create({
    value: 0
});

var to = Ember.Object.create({
    from: from,
    valueBinding: ConditionalBinding
        .from('from.value')
        .pauseIfTrue('pausingProperty'),
        // Default:
        // .onResumeSetBothTo('latest')
    pausingProperty: false
});

While pausingProperty is set to true, the binding between from and to will not be synchonized in either direction. Upon resume, the binding will be synchronized to the latest-wins (you can also use .onResumeSetBothTo('to') or .onResumeSetBothTo('from') to explicitly set synching from to or from).

If you want to only pause in one direction, you can add onlyPause('from') or onlyPause('to'):

var to = Ember.Object.create({
    from: from,
    valueBinding: ConditionalBinding
        .from('from.value')
        .pauseIfTrue('pausingProperty')
        .onlyPause('from')
        .onResumeSetBothTo('from'),
    pausingProperty: false
});
于 2013-03-05T17:59:00.417 回答