我一直在研究插件开发,注意到在像 Discourse 翻译器 这样的案例中,通过 findAncestorModel() 获取小部件模型后,都会先检查结果是否存在再继续进行。我在源代码中也看到了类似的做法,示例:
_getTopicUrl() {
const post = this.findAncestorModel();
return post ? post.get("topic.url") : null;
},
但也有不少情况并未检查祖先模型是否存在,如下几行:
const post = this.findAncestorModel();
const controller = this.register.lookup("controller:topic");
return post
.get("topic.postStream")
.filterUpwards(this.attrs.id)
.then(() => {
controller.updateQueryParams();
});
findAncestorModel() 返回结果的存在性有多可靠?这是否取决于我们所在的小部件类型?还是说,即使在像帖子菜单这样看似极不可能出现 null 的情况下,始终处理 null 响应也是良好的实践?