Aurelia:更改为空值时删除数组元素

时间:2016-10-27 10:01:01

标签: aurelia aurelia-binding

我有一个绑定到输入元素的字符串数组:

Visual visual;  
public MainPage()
{
    this.InitializeComponent();
    visual = ElementCompositionPreview.GetElementVisual(txtanimation);
    Compositor compositor = ElementCompositionPreview.GetElementVisual(txtanimation).Compositor;
    ImplicitAnimationCollection animationCollection = compositor.CreateImplicitAnimationCollection();
    Vector3KeyFrameAnimation offsetAnimation = compositor.CreateVector3KeyFrameAnimation();
    offsetAnimation.Target = "Offset";
    offsetAnimation.Duration = TimeSpan.FromSeconds(2.5);
    offsetAnimation.InsertExpressionKeyFrame(1.0f, "This.FinalValue");    
    animationCollection["Offset"] = offsetAnimation;
    visual.ImplicitAnimations = animationCollection; 
}

private void btnanimate_Click(object sender, RoutedEventArgs e)
{        
     visual.Offset=visual.Offset+ new System.Numerics.Vector3(0f, 400f, 0f);
}

我需要在删除输入内容时删除元素,而不使用脏检查。

这听起来很简单 - 只需从input.delegate处理程序中删除具有空值的元素,遗憾的是,由于Aurelia bug #527,这不起作用。以下是尝试这种方法的要点:https://gist.run/?id=e49828b236d979450ce54f0006d0fa0a

我试图通过使用queueTask来推迟删除数组元素来解决这个问题,但无济于事。而且由于开发人员关闭了这个bug,因为据他们说它是一个完全不相关的问题的副本,我想它不会很快得到修复。

我不知道如何实现这一点,所以欢迎任何建议。

2 个答案:

答案 0 :(得分:1)

这里绝对不需要任何脏检查! :)

以下是适用于您的方案的工作演示:https://gist.run/?id=20d92afa1dd360614147fd381931cb17

  • 不再需要$ parent。它与1.0之前的Aurelia版本有关。
  • 如果使用变量而不是数组索引,则可以利用输入提供的双向数据绑定。
<template>
  <div repeat.for="msg of messages">
    <input type="text" value.bind="msg" input.delegate="onMessageChanged(msg, $index)">
  </div>
</template>

因此,您的onChange事件可以简化为:

  • msg保存当前输入的实际值。
  • i索引将用于删除。
export class App {
  messages = ['Alpha','Bravo','Charlie','Delta','Echo'];

  onMessageChanged(msg, i){
    if (!msg || msg.length === 0) {
      this.messages.splice(i, 1); 
    }
  }
}

有一个关于类似问题的相关问题。 This answer可能会为您提供有关主要想法的更多详细信息。

答案 1 :(得分:-2)

好的,所以这个解决方案不是使用bug(在本例中)aurelia双向绑定,而是使用单向绑定并设置input.delegate处理程序的值:

https://gist.run/?id=2323c09ec9da989eed21534f177bf5a8

@marton的答案似乎乍一看,但它实际上禁用了双向绑定,因此对输入的任何更改都不会复制到数组中。但它给了我一个重要的暗示如何解决这个问题。 相当于这个HTML代码:

<div repeat.for="msg of messages">
    <input type="text" value.bind="msg">
</div>

就是这样:

for (let msg of messages) {
  msg = 'something else'; // note: this does not change the contents of the array
}

有关详细信息,请参阅issue #444

因此,这会强制单向绑定。要在@marton解决方案中修复此问题,我们只需要更改input.delegate处理程序中的值:

onMessageChanged(msg, i){
  if (!msg || msg.length === 0) {
    this.messages.splice(i, 1);//delete the element 
  }
  else {
    this.messages[i] = msg;//change the value
  }
}
相关问题