代码之家  ›  专栏  ›  技术社区  ›  Brandon

如何使用Aurelia在取消选中和选中时调用函数

  •  10
  • Brandon  · 技术社区  · 9 年前

    用户可以选中/取消选中每个项目。我想做的是:

    1. 当选中某个项时,它会将该项的ID推入数组
    2. 当一个项目被取消选中时,它将从数组中删除该项目的ID

    我只需要知道如何根据它是否被选中来调用它。我试过“checked.delegate”和“checked.trigger”,但似乎无法实现。

    只需定期单击即可。委托不起作用,因为我无法保持它是真是假的状态,也无法为所有变量设置变量,因为我并不总是知道哪些项将从API传入。有什么建议吗?

    3 回复  |  直到 9 年前
        1
  •  25
  •   Ashley Grant    9 年前

    尝试 change.delegate change.trigger 这样地:

    VM方法:

    logchange(value) {
      console.log(value);
    }
    

    视图:

    <input type="checkbox" change.delegate="logchange($event.target.checked)" />
    
        2
  •  0
  •   AnorZaken    3 年前

    有(从什么时候开始?)如何准确地解决这个具体问题的官方文档: https://aurelia.io/docs/binding/checkboxes#array-of-numbers


    Aurelia可以直接绑定到您的数组并为您处理一切-您所需要做的就是告诉Aurelia要重复的元素的哪个属性存储在数组中( id ).

    其要点:

    应用.js

      export class App {
        products = [
          { id: 0, name: 'Motherboard' },
          { id: 1, name: 'CPU' },
          { id: 2, name: 'Memory' },
        ];
      
        selectedProductIds = [];
      }
    

    应用.html

      <template>
        <form>
          <h4>Products</h4>
          <label repeat.for="product of products">
            <input type="checkbox" model.bind="product.id" checked.bind="selectedProductIds">
            ${product.id} - ${product.name}
          </label>
          <br>
          Selected product IDs: ${selectedProductIds}
        </form>
      </template>
    

        3
  •  -1
  •   dimlucas    9 年前

    有一种方法可以做到这一点,那就是借助于设置器。假设您有这样一个复选框:

    <input type="checkbox">

    在视图模型中创建私有字段,然后用getter和setter将其包装起来:

    get isChecked(){
        return this._isChecked;
    }
    
    set isChecked(value){
        this._isChecked = value;
        //enter your extra logic here, no need for an event handler
    }
    
    private _isChecked: boolean;
    

    然后绑定 isChecked

    <input type="checkbox" checked.bind="isChecked">

    实现这一目标的另一种更非传统的方法是使用 @bindable 这样的装饰:

    @bindable isChecked: boolean;

    这是非常规的,因为你可能不想要 已选中 可绑定,但装饰器允许您访问 isCheckedChanged 方法:

    isCheckedChanged(newValue, oldValue){
         //Logic here
    }
    

    当然还有 change 你可以抓住的事件 change.trigger change.delegate 但这已经在另一个答案中提到了