首页 > 解决方案 > 双向绑定不适用于 Aurelia 自定义属性

问题描述

我正在尝试实施Jeremy Danyow 为脏检查提供的解决方案。我正在使用 TypeScript,所以我尽可能地调整了他的代码。出于某种原因,isDirty我的 VM 上的标志没有更新。这是我所拥有的:

Agency.ts - (我的虚拟机)

export class Agency {
    public isDirty : boolean = false;
    public agency : IAgency = null;

    ...
}

Agency.html - (我的观点)

<template>
   <require from="../resources/attributes/dirty"></require>
    ${isDirty}                                <== Always displays false
    <form dirty.two-way="isDirty">            <== have also tried dirty.bind
         <div class="input-group">
               <label>Agency Name</label>
               <input type="text" value.bind="agency.name" />
         </div>
         ... 
    </form>
    <div if.bind="isDirty">
         <button>Save Changes</button>
         <button>Undo Changes</button>
    </div>
</template>

脏.ts - (属性)

import {bindable, bindingMode} from 'aurelia-framework';

export class DirtyCustomAttribute{
   private view: any;
   private bindings: any[] = [];
   @bindable({defaultBindingMode: bindingMode.twoWay }) value: any;

   static inject = [Element]
   constructor(public element : HTMLElement) {}

   created(view) {
      this.view = view;
   }

   bind() {  
    this.bindings = this.view.bindings
        .filter(b => b.mode === bindingMode.twoWay && this.element.contains(b.target));

    let i = this.bindings.length;
    let self = this;
    while (i--) {
        let binding = this.bindings[i];
        binding.dirtyTrackedUpdateSource = binding.updateSource;
        binding.updateSource = function (newValue) {
            this.dirtyTrackedUpdateSource(newValue);
            if (!self.value) {
                self.value = true;
            }
        }
    }
   }

   unbind() { // See code in referenced link }
}

因此,使用日志记录,我可以看到updateSource()正在调用代码并且self.value正在设置标志。但是,div在我的视图中带有按钮的 永远不会显示,并且${isDirty}模板始终显示为 false。看起来这dirty.two-way="isDirty"不是应该的双向绑定。

我哪里错了?

更新

所以看起来它可能是由于组合,所以我将添加额外的代码来展示它是如何组合的。

外壳.ts

export class Shell
{
    public agencies : IAgency[] = []; //loaded in activate
    public tablist : any[] = [
        {title: "Detail", vm: PLATFORM.moduleName("./agency") },
         ...
    ];
    public selectedAgency : IAgency = null;
    public selectedVM : any = this.tablist[0];

}

外壳.html

<template>
    ...
    <compose view-model.bind="selectedVM.vm" model.bind="selectedAgency"></compose>
</template>

代理.ts(附加)

activate(model){
    this.agency = model;
    ...
}

标签: aurelia

解决方案


推荐阅读