【发布时间】:2016-01-14 15:37:10
【问题描述】:
我仍在继续我的 Angular2(beta 1)新手之旅,我正在尝试了解如何正确实现 2 向绑定,而不会让我的应用陷入无限循环。
请在此 Plunker 上找到示例复制品:http://plnkr.co/edit/83NeiUCEpPvYvUXIkl0g。只需运行并单击按钮即可。
我的场景:
- 一个指令包装了 Ace 代码编辑器并公开了一个
text属性和一个textChanged事件。 - (XML)编辑器组件使用此指令。它应该能够响应底层编辑器中的更改以更新其 XML 代码,并根据其 XML 代码在底层编辑器中设置新文本。
我的问题是,每当编辑器组件以编程方式设置其xml 属性时,都会触发底层 Ace 编辑器中的更改,进而触发 text-changed 事件,该事件又由编辑器组件的回调处理,等等。这会生成一个无限循环,您可以看到编辑器的文本闪烁。我在这里做错了什么?
这是指令的代码:
import {Component,Directive,EventEmitter,ElementRef} from 'angular2/core';
declare var ace: any;
@Directive({
selector: "ace-editor",
inputs: [
"text"
],
outputs: [
"textChanged"
]
})
export class AceDirective {
private editor : any;
public textChanged: EventEmitter<string>;
set text(s: string) {
if (s === undefined) return;
let sOld = this.editor.getValue();
if (sOld === s) return;
this.editor.setValue(s);
this.editor.clearSelection();
this.editor.focus();
}
get text() {
return this.editor.getValue();
}
constructor(elementRef: ElementRef) {
var dir = this;
this.textChanged = new EventEmitter<string>();
let el = elementRef.nativeElement;
this.editor = ace.edit(el);
let session = this.editor.getSession();
session.setMode("ace/mode/xml");
session.setUseWrapMode(true);
this.editor.on("change", (e) => {
let s = dir.editor.getValue();
dir.textChanged.next(s);
});
}
}
这里是编辑器组件:
import {Component,EventEmitter} from "angular2/core";
import {AceDirective} from "./ace.directive";
@Component({
selector: "my-editor",
directives: [AceDirective],
template: `<div style="border:1px solid red">
<ace-editor id="editor" [text]="xml" (textChanged)="onXmlChanged($event)"></ace-editor>
</div>
<div><button (click)="changeXml()">set xml</button></div>`,
inputs: [
"xml"
]
})
export class EditorComponent {
private _xml: string;
// using a property here so that I can set a breakpoint
public set xml(s: string) {
this._xml = s;
}
public get xml() : string {
return this._xml;
}
constructor() {
this._xml = "";
}
public onXmlChanged(xml: string) {
this._xml = xml;
}
// an action which somehow changes the XML content
public changeXml() {
this._xml = "<x>abc</x>";
}
}
【问题讨论】:
标签: typescript angular