aurelia bindingcontext 被父级覆盖

aurelia bindingcontext gets overridden by parent

回答如下

我遇到了 Aurelia bindingcontext 被父组件替换的问题。

我有第一个组件,它有一个 sourceItem 属性 在它的视图中绑定:

${sourceItem.Name}

这显示了正确的值 "Parent name"..

此组件有一个 router-view,其中创建了另一个组件。我可以看到这个子组件的创建没有问题。问题是这个子组件还有一个 sourceItem 属性 以同样的方式绑定在它的视图中。

${sourceItem.Name}

应该 显示值 "Child name" 但是虽然我可以看到第二个 sourceItem 被正确创建,视图显示父绑定上下文的值:"Parent name"

如果我更改 sourceItem 之一的名称(例如 sourceItem1),一切正常。知道我是不是犯了什么错误,或者某处是否存在错误?

非常感谢!

编辑以获取更多信息 我注意到,当导航到子路线时,问题出现在我身上。但是当我在浏览器的栏中输入完整的 URL 并加载页面时,绑定工作正常。当我检查 bindingContext 和 overrideContext(在 bind() 方法中)时,结果完全相同。所以看起来可能是时间问题...

我猜这是按照文档中所述的方式工作的:

The "scope" in aurelia is made up of two objects: the bindingContext (almost always a view-model instance) and the overrideContext which can be thought of as an "overlay" of the bindingContext. Properties on the overrideContext "override" corresponding properties on the bindingContext. It is actually rare for there to be a property on the overrideContext that is "hiding" a property on the bindingContext beneath. ...

参见:http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-how-it-works/3

我也在 github 上发布了这个问题,我得到了答案。 在我的例子中,我有一些异步代码在我的子路由视图模型的激活方法中从服务器检索数据。问题显然是由于服务器在触发绑定引擎之前没有return,所以它获取了它可以找到的信息(父绑定上下文)。

我只需要 return 激活方法的承诺,这样 aurelia 会在启动绑定引擎之前等待 return 的承诺...