我正在从KnockoutJS迁移到Aurelia,并且很难弄清楚如何从视图中换出一些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);
});
在上面的代码中,传递给AJAX请求的url的self.type()
是某些设置的名称。以下是一些设置的示例:
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
属性来呈现该视图并在AJAX请求中返回它。示例设置视图如下:
@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请求并看看我在那里做什么,它应该更有意义。我注入了这个HTML的<div>
,如下所示:
<div id="settings-details"></div>
我想弄清楚如何在Aurelia做到这一点。我看到我可以使用Aurelia的templatingEngine.enhance({ element: elementToBind, bindingContext: this });
而不是Knockout的ko.applyBindings(self, elementToBind);
,所以我认为应该将新属性绑定到视图模型。但是,我不知道如何处理来自设置编辑器模板的脚本。我想我可以尝试保持我已经拥有的相同逻辑(使用jQuery添加/删除脚本等)...但我希望有一个更清晰/更优雅的解决方案与Aurelia。我看了slots
,但我认为这不适用于此,但我可能错了。
答案 0 :(得分:1)
正如评论中所讨论的,我对other question的回答应该在这里诀窍。鉴于此runtime-view
元素:
打字稿
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,其中包含任何类型的绑定,自定义元素和其他aurelia行为。
它将编译此html并绑定到它在bind()
中收到的bindingContext - 这将是您声明它的视图的viewModel。
<runtime-view html.bind="dynamicHtml">
</runtime-view>
在视图模型中给出someObject
:
this.someObject.foo = "bar";
和dynamicHtml
一样:
this.dynamicHtml = "<div>${foo}</div>";
这将在正常的Aurelia视图中呈现为您所期望的:
<runtime-view html.bind="dynamicHtml" context.bind="someObject">
</runtime-view>
重新分配html
或context
将触发它重新编译。为了让您了解可能的用例,我在使用Monaco编辑器的项目中使用它来从Aurelia应用程序本身动态创建Aurelia组件,此元素将提供实时预览(在编辑器旁边)和当我在应用程序的其他地方使用它时,也编译+渲染存储的html / js / json。