我正在从 KnockoutJS 迁移到 Aurelia,并且很难弄清楚如何从 View 中换出一些 HTML/JS。我有一些现有的 Knockout 代码如下:
$.ajax({
url: "/admin/configuration/settings/get-editor-ui/" + replaceAll(self.type(), ".", "-"),
type: "GET",
dataType: "json",
async: false
})
.done(function (json) {
// Clean up from previously injected html/scripts
if (typeof cleanUp == 'function') {
cleanUp(self);
}
// Remove Old Scripts
var oldScripts = $('script[data-settings-script="true"]');
if (oldScripts.length > 0) {
$.each(oldScripts, function () {
$(this).remove();
});
}
var elementToBind = $("#form-section")[0];
ko.cleanNode(elementToBind);
var result = $(json.content);
// Add new HTML
var content = $(result.filter('#settings-content')[0]);
var details = $('<div>').append(content.clone()).html();
$("#settings-details").html(details);
// Add new Scripts
var scripts = result.filter('script');
$.each(scripts, function () {
var script = $(this);
script.attr("data-settings-script", "true");//for some reason, .data("block-script", "true") doesn't work here
script.appendTo('body');
});
// Update Bindings
// Ensure the function exists before calling it...
if (typeof updateModel == 'function') {
var data = ko.toJS(ko.mapping.fromJSON(self.value()));
updateModel(self, data);
ko.applyBindings(self, elementToBind);
}
//self.validator.resetForm();
switchSection($("#form-section"));
})
.fail(function (jqXHR, textStatus, errorThrown) {
$.notify(self.translations.getRecordError, "error");
console.log(textStatus + ': ' + errorThrown);
});
在上面的代码中,self.type()
传递给 AJAX 请求的 url 是一些设置的名称。以下是一些设置的示例:
public class DateTimeSettings : ISettings
{
public string DefaultTimeZoneId { get; set; }
public bool AllowUsersToSetTimeZone { get; set; }
#region ISettings Members
public string Name => "Date/Time Settings";
public string EditorTemplatePath => "Framework.Web.Views.Shared.EditorTemplates.DateTimeSettings.cshtml";
#endregion ISettings Members
}
我用那个EditorTemplatePath
属性来呈现该 View 并在 AJAX 请求中返回它。示例设置 View 如下:
@using Framework.Web
@using Framework.Web.Configuration
@inject Microsoft.Extensions.Localization.IStringLocalizer T
@model DateTimeSettings
<div id="settings-content">
<div class="form-group">
@Html.LabelFor(m => m.DefaultTimeZoneId)
@Html.TextBoxFor(m => m.DefaultTimeZoneId, new { @class = "form-control", data_bind = "value: defaultTimeZoneId" })
@Html.ValidationMessageFor(m => m.DefaultTimeZoneId)
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(m => m.AllowUsersToSetTimeZone, new { data_bind = "checked: allowUsersToSetTimeZone" }) @T[FrameworkWebLocalizableStrings.Settings.DateTime.AllowUsersToSetTimeZone]
</label>
</div>
</div>
<script type="text/javascript">
function updateModel(viewModel, data) {
viewModel.defaultTimeZoneId = ko.observable("");
viewModel.allowUsersToSetTimeZone = ko.observable(false);
if (data) {
if (data.DefaultTimeZoneId) {
viewModel.defaultTimeZoneId(data.DefaultTimeZoneId);
}
if (data.AllowUsersToSetTimeZone) {
viewModel.allowUsersToSetTimeZone(data.AllowUsersToSetTimeZone);
}
}
};
function cleanUp(viewModel) {
delete viewModel.defaultTimeZoneId;
delete viewModel.allowUsersToSetTimeZone;
}
function onBeforeSave(viewModel) {
var data = {
DefaultTimeZoneId: viewModel.defaultTimeZoneId(),
AllowUsersToSetTimeZone: viewModel.allowUsersToSetTimeZone()
};
viewModel.value(ko.mapping.toJSON(data));
};
</script>
现在,如果您返回 AJAX 请求,看看我在那里做了什么,它应该更有意义。有一个 <div>
我在其中注入(inject)此 HTML,如下所示:
<div id="settings-details"></div>
我正在尝试弄清楚如何在 Aurelia 中执行此操作。我发现我可以使用 Aurelia 的 templatingEngine.enhance({ element: elementToBind, bindingContext: this });
而不是 Knockout 的 ko.applyBindings(self, elementToBind);
所以我认为应该将新属性绑定(bind)到 View 模型。但是,我不知道如何处理设置编辑器模板中的脚本。我想我可以尝试保持我已经拥有的相同逻辑(使用 jQuery 添加/删除脚本等)......但我希望 Aurelia 有一个更清晰/更优雅的解决方案。我看了slots
,但我认为这不适用于此处,尽管我可能是错的。
最佳答案
正如评论中所讨论的,我对您的回答other question应该在这里做的伎俩。鉴于此 runtime-view
元素:
typescript
import { bindingMode, createOverrideContext } from "aurelia-binding";
import { Container } from "aurelia-dependency-injection";
import { TaskQueue } from "aurelia-task-queue";
import { bindable, customElement, inlineView, ViewCompiler, ViewResources, ViewSlot } from "aurelia-templating";
@customElement("runtime-view")
@inlineView("<template><div></div></template>")
export class RuntimeView {
@bindable({ defaultBindingMode: bindingMode.toView })
public html: string;
@bindable({ defaultBindingMode: bindingMode.toView })
public context: any;
public el: HTMLElement;
public slot: ViewSlot;
public bindingContext: any;
public overrideContext: any;
public isAttached: boolean;
public isRendered: boolean;
public needsRender: boolean;
private tq: TaskQueue;
private container: Container;
private viewCompiler: ViewCompiler;
constructor(el: Element, tq: TaskQueue, container: Container, viewCompiler: ViewCompiler) {
this.el = el as HTMLElement;
this.tq = tq;
this.container = container;
this.viewCompiler = viewCompiler;
this.slot = this.bindingContext = this.overrideContext = null;
this.isAttached = this.isRendered = this.needsRender = false;
}
public bind(bindingContext: any, overrideContext: any): void {
this.bindingContext = this.context || bindingContext.context || bindingContext;
this.overrideContext = createOverrideContext(this.bindingContext, overrideContext);
this.htmlChanged();
}
public unbind(): void {
this.bindingContext = null;
this.overrideContext = null;
}
public attached(): void {
this.slot = new ViewSlot(this.el.firstElementChild || this.el, true);
this.isAttached = true;
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
public detached(): void {
this.isAttached = false;
if (this.isRendered) {
this.cleanUp();
}
this.slot = null;
}
private htmlChanged(): void {
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
private contextChanged(): void {
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
private tryRender(): void {
if (this.isAttached) {
if (this.isRendered) {
this.cleanUp();
}
try {
this.tq.queueMicroTask(() => {
this.render();
});
} catch (e) {
this.tq.queueMicroTask(() => {
this.render(`<template>${e.message}</template>`);
});
}
}
}
private cleanUp(): void {
try {
this.slot.detached();
} catch (e) {}
try {
this.slot.unbind();
} catch (e) {}
try {
this.slot.removeAll();
} catch (e) {}
this.isRendered = false;
}
private render(message?: string): void {
if (this.isRendered) {
this.cleanUp();
}
const template = `<template>${message || this.html}</template>`;
const viewResources = this.container.get(ViewResources) as ViewResources;
const childContainer = this.container.createChild();
const factory = this.viewCompiler.compile(template, viewResources);
const view = factory.create(childContainer);
this.slot.add(view);
this.slot.bind(this.bindingContext, this.overrideContext);
this.slot.attached();
this.isRendered = true;
}
}
ES6
import { bindingMode, createOverrideContext } from "aurelia-binding";
import { Container } from "aurelia-dependency-injection";
import { TaskQueue } from "aurelia-task-queue";
import { DOM } from "aurelia-pal";
import { bindable, customElement, inlineView, ViewCompiler, ViewResources, ViewSlot } from "aurelia-templating";
@customElement("runtime-view")
@inlineView("<template><div></div></template>")
@inject(DOM.Element, TaskQueue, Container, ViewCompiler)
export class RuntimeView {
@bindable({ defaultBindingMode: bindingMode.toView }) html;
@bindable({ defaultBindingMode: bindingMode.toView }) context;
constructor(el, tq, container, viewCompiler) {
this.el = el;
this.tq = tq;
this.container = container;
this.viewCompiler = viewCompiler;
this.slot = this.bindingContext = this.overrideContext = null;
this.isAttached = this.isRendered = this.needsRender = false;
}
bind(bindingContext, overrideContext) {
this.bindingContext = this.context || bindingContext.context || bindingContext;
this.overrideContext = createOverrideContext(this.bindingContext, overrideContext);
this.htmlChanged();
}
unbind() {
this.bindingContext = null;
this.overrideContext = null;
}
attached() {
this.slot = new ViewSlot(this.el.firstElementChild || this.el, true);
this.isAttached = true;
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
detached() {
this.isAttached = false;
if (this.isRendered) {
this.cleanUp();
}
this.slot = null;
}
htmlChanged() {
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
contextChanged() {
this.tq.queueMicroTask(() => {
this.tryRender();
});
}
tryRender() {
if (this.isAttached) {
if (this.isRendered) {
this.cleanUp();
}
try {
this.tq.queueMicroTask(() => {
this.render();
});
} catch (e) {
this.tq.queueMicroTask(() => {
this.render(`<template>${e.message}</template>`);
});
}
}
}
cleanUp() {
try {
this.slot.detached();
} catch (e) {}
try {
this.slot.unbind();
} catch (e) {}
try {
this.slot.removeAll();
} catch (e) {}
this.isRendered = false;
}
render(message) {
if (this.isRendered) {
this.cleanUp();
}
const template = `<template>${message || this.html}</template>`;
const viewResources = this.container.get(ViewResources);
const childContainer = this.container.createChild();
const factory = this.viewCompiler.compile(template, viewResources);
const view = factory.create(childContainer);
this.slot.add(view);
this.slot.bind(this.bindingContext, this.overrideContext);
this.slot.attached();
this.isRendered = true;
}
}
以下是您可以使用它的一些方法:
dynamicHtml
是 ViewModel 上的一个属性,包含任意生成的 html,其中包含任何类型的绑定(bind)、自定义元素和其他 aurelia 行为。
它将编译此 html 并绑定(bind)到它在 bind()
中接收到的 bindingContext - 这将是您在其中声明它的 View 的 viewModel。
<runtime-view html.bind="dynamicHtml">
</runtime-view>
给定一个 someObject
在 View 模型中:
this.someObject.foo = "bar";
还有一个 dynamicHtml
像这样:
this.dynamicHtml = "<div>${foo}</div>";
这将按照您在普通 Aurelia View 中的预期呈现:
<runtime-view html.bind="dynamicHtml" context.bind="someObject">
</runtime-view>
重新分配 html
或 context
将触发它重新编译。只是为了让您了解可能的用例,我在带有 monaco 编辑器的项目中使用它从 Aurelia 应用程序本身动态创建 Aurelia 组件,并且此元素将提供实时预览(在编辑器旁边)和当我在应用程序的其他地方使用它时,还会编译+呈现存储的 html/js/json。
关于javascript - 如何在 Aurelia 中注入(inject)/替换部分 View 和 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50184788/