pfaffman
(Jay Pfaffman)
2020 年2 月 16 日 16:40
1
我擅长系统管理。在 Rails 方面我也不算差。但说到 JavaScript、Ember 和 CSS,我简直就是个原始人。
在一个用于控制谁能发送私信(PM)的插件中,我试图在用户没有发送私信权限时,在其个人主页上添加一个按钮。通过将内容放入 assets/javascripts/discourse/templates/connectors/user-summary-stat/my-clever-name.hbs,我可以在想要的位置添加文本。(大家欣喜若狂!)
我注意到 https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/templates/user/messages.hbs#L3 使用了
{{#if showNewPM}}
我希望能直接在 my-clever-name.hbs 中使用该变量,但该变量并未定义。
我想我可能需要在与 hbs 文件相同的目录下创建一个 my-clever-name.js.es6 文件,并包含……某些内容,或者添加一些代码来定义该变量,以便我能访问它。但我已经重读了开发者指南几遍,也尝试模仿一些看起来在做同样事情的插件中的代码,却仍未弄清楚具体该怎么做。
你好,Jay,
我听说有人称 EmberJS 是“一门独立的语言”!
你需要的是计算属性(Computed Property):
In a nutshell, computed properties let you declare functions as properties. You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property. You can then use it the same way you would...
虽然 Discourse 源码的语法和导入方式略有不同,但最好还是参考一个示例。这是我代码中的一小部分:
https://github.com/paviliondev/discourse-zspace/blob/cc8893c14a9b1c5d4f6552f8f6b12ea9ac7ac643/assets/javascripts/discourse/components/activity-file-edit.js.es6#L10
pfaffman
(Jay Pfaffman)
2020 年2 月 16 日 19:20
3
所以 @discourseComputed("uploading") 的作用是让 uploading 可以在 hbs 模板中使用吗?有点像 Ember 中的:
fullName: computed('firstName', 'lastName', function() {
return `${this.firstName} ${this.lastName}`;
})
那我应该创建 assets/javascripts/discourse/components/my-plugin.js.es6 并扩展某个东西吗?似乎应该有一种方法,可以直接“启用”我正在扩展的那个模板所访问的相同变量。哦!也许扩展“那个东西”会让这些变量在我的组件中可用?
我是不是应该退一步,花一周时间学习 Ember 教程?
所以,这是在设置一个名为 ‘fullName’ 的计算属性,当 ‘firstName’ 或 ‘lastName’ 发生变化时,该属性会随之更新。它的值即为函数的返回值。
pfaffman
(Jay Pfaffman)
2020 年2 月 16 日 21:02
5
感谢您的耐心!
我想我理解了,但我不明白的是,如何创建可以在我的模板中访问的值。
assets/javascript/discourse/components/user-private-messages.js.es6:
import discourseComputed from "discourse-common/utils/decorators";
import User from "discourse/controllers/user";
export default Ember.Component.extend(User, {
classNames: ["restrict-pms"],
myFunThing: "this is text in my fun thing",
@discourseComputed("myvalue")
someThing(myvalue) {
return true;
}
});
Template.registerHelper("log", function(something){
console.log(something);
});
我想我真正想问的是(可能不太清楚),我可以在 assets/javascripts/discourse/templates/connectors/user-profile-controls/add-link-to-subscription.hbs 中放什么,以便能够访问 myFunThing 或 myvalue?
与您的组件 JS 对应的模板可以通过将计算属性包含在双大括号中来直接引用它:
{{fullName}}
pfaffman
(Jay Pfaffman)
2020 年2 月 17 日 20:00
7
上述代码位于 assets/javascript/discourse/components/user-private-messages.js.es6。
我希望能够在 assets/javascripts/discourse/templates/connectors/user-profile-controls/add-link-to-subscription.hbs 中使用 {{myFunThing}} 和/或 {{myvalue}},但它们显示为未定义。
我认为可能是这两个文件中的某一个位置不对(我注意到上述 hbs 文件中的其他文本确实渲染在了 /u/username/summary 页面上,只是没有显示 myFunThing),或者是我导入了错误的类,和/或扩展了错误的组件。
抱歉,Jay 现在有点忙,但你可以做的是在连接器的 hbs 文件中,直接在你的组件 hbs 里连接组件,例如:
{{my-component}}
(根据需要添加参数)
系统随后会在 templates/components 和 /components 目录下查找 my-component.hbs。
或者,你也可以在连接器目录下的 js 文件中设置该属性,但就我个人风格而言,更倾向于前者。
我知道这是去年发的,但你后来解决了吗,@pfaffman ?