设计“插件” - 如何在 JSON 中传递对象方法?
我不确定这是否可能,或者更重要的是良好的设计。 对两者的反馈表示赞赏。
我们有一个通过“插件”添加功能元素的前端。 插件设计是一个带有一些数据和一些方法的 JavaScript 对象,如下所示:
function FeedbackPlugin(){
return {
name: "Feedback",
help: "Provide feedback on any element of the site",
...
showForm : function(_feedbackType) {
...
},
...
messageCallbacks: [{callbackKey:"ProvideFeedback",callbackHandler:showForm}]
};
}
框架加载每个插件,然后迭代 messageCallbacks 将 comet 事件与插件方法联系起来。
遗憾的是上面的代码不起作用。当框架尝试注册插件时,该插件的 showForm 方法不在范围内。我认为我们可能需要传递一个指向现有插件实例的 showForm 方法的指针...
- javascript中有什么方法可以 以某种方式使这个方法静态?
- 该方法是否应该存在于外部 为了方便起见的插件?
谢谢。
I'm not sure if this is possible or maybe more imporantly good design.
Feedback on both appreciated.
We have a front end that we add functional elements to through 'plugins'.
The plugin design is a javascript object with some data and some methods as below:
function FeedbackPlugin(){
return {
name: "Feedback",
help: "Provide feedback on any element of the site",
...
showForm : function(_feedbackType) {
...
},
...
messageCallbacks: [{callbackKey:"ProvideFeedback",callbackHandler:showForm}]
};
}
The framework loads each plugin and then iterates over the messageCallbacks to tie comet events to plugin methods.
Sadly the code above does not work. The plugin's showForm method is not in scope when the framework tries to register it. I think we may need to pass a pointer to the showForm method of an existing plugin instance...
- Is there any way in javascript to
somehow make this method static? - Should the method just live outside
the plugin for convenience sake?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果加载的每个插件都是静态的(不包含变化的数据),则将它们加载为脚本而不是 JSON。如果存在动态数据,则将动态数据与静态函数分开,并仅以 JSON 形式发送数据。
If each plugin being loaded is static (contains no varying data), then load them as scripts instead of JSON. If there is data that's dynamic, then separate the dynamic data from the static functions, and send only the data as JSON.