在我的 Knockout.js 模板中,如果我可以访问 View 模型上对象的属性会很方便:
<span data-bind="text: account.shortName"></span>
这行不通。该元素为空。但是,我可以这样做:
<div data-bind="with: account">
<span data-bind="text: shortName"></span>
</div>
有什么办法解决这个问题吗?我必须在任何地方都使用 with
吗?多余的元素也必须使用吗?
最佳答案
如果 account
是可观察的,那么您真的应该使用 with
绑定(bind),就像您已经拥有它一样,或者使用计算的可观察对象来访问该属性。当然,这有点冗长,但必须这样做。
使用像 someObservable().someProperty
这样的表达式只会导致头痛和困惑,应该避免。例如,如果你确实使用了这个并且 someProperty
恰好是可观察的,你可能会注意到当 someObservable
改变时有些不对劲。绑定(bind)将不会更新为使用新值的 someProperty
,我希望您能明白原因。
您可以通过创建一个函数来更轻松地以安全的方式创建计算可观察对象。
ko.observable.fn.property = function (name) {
return ko.computed({
read: function () {
var parentValue = this();
if (parentValue)
return ko.utils.unwrapObservable(parentValue[name]);
},
write: function (value) {
var parentValue = this(), property;
if (parentValue) {
property = parentValue[name];
if (ko.isWriteableObservable(property))
property(value);
}
},
owner: this
});
};
然后你可以在你的绑定(bind)中使用它:
<span data-bind="text: account.property('shortName')"></span>
关于knockout.js - Knockout 似乎不喜欢 bind 中的 object.property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622001/