我一直希望在 Meteor 中使用继承,但我在文档或 Stack Overflow 上找不到任何关于它的信息。
是否可以让模板从另一个抽象模板或类继承属性和方法?
我一直希望在 Meteor 中使用继承,但我在文档或 Stack Overflow 上找不到任何关于它的信息。
是否可以让模板从另一个抽象模板或类继承属性和方法?
我认为简短的答案是否定的,但这里有一个更长的答案:
我为在模板之间共享功能所做的一件事是定义一个助手对象,然后将其分配给多个模板,如下所示:
var helpers = {
displayName: function() {
return Meteor.user().profile.name;
},
};
Template.header.helpers(helpers);
Template.content.helpers(helpers);
var events = {
'click #me': function(event, template) {
// handle event
},
'click #you': function(event, template) {
// handle event
},
};
Template.header.events(events);
Template.content.events(events);
确切地说,它不是继承,但它确实使您能够在模板之间共享功能。
如果您希望所有模板都可以访问帮助程序,您可以像这样定义一个全局帮助程序(请参阅https://github.com/meteor/meteor/wiki/Handlebars):
Handlebars.registerHelper('displayName',function(){return Meteor.user().profile.name;});
我已经在这里回答了这个问题。虽然该解决方案不使用inheritance
,但它允许您轻松地跨模板共享事件和帮助程序。
简而言之,我定义了一个extendTemplate
函数,它接收一个模板和一个带有帮助器和事件作为参数的对象:
extendTemplate = (template, mixin) ->
helpers = ({name, method} for name, method of mixin when name isnt "events")
template[obj.name] = obj.method for obj in helpers
if mixin.events?
template.events?.call(template, mixin.events)
template
有关更多详细信息和示例,请参阅我的其他答案。
Recently, I needed the same functionality in my app so I've decided to create my own package that will do that job out of the box. Although it's still work in progress, you can give it a go.
Basically, the entire method is as follows:
// Defines new method /extend
Template.prototype.copyAs = function (newTemplateName) {
var self = this;
// Creating new mirror template
// Copying old template render method to keep its template
var newTemplate = Template.__define__(newTemplateName, self.__render);
newTemplate.__initView = self.__initView;
// Copying helpers
for (var h in self) {
if (self.hasOwnProperty(h) && (h.slice(0, 2) !== "__")) {
newTemplate[h] = self[h];
}
}
// Copying events
newTemplate.__eventMaps = self.__eventMaps;
// Assignment
Template[newTemplateName] = newTemplate;
};
In your new template (new_template.js) in which you want to extend your abstract one, write following:
// this copies your abstract template to your new one
Template.<your_abstract_template_name>.copyAs('<your_new_template_name>');
Now, you can simply either overwrite your helpers or events (in my case it's photos
helper), by doing following:
Template.<your_new_template_name>.photos = function () {
return [];
};
Your will refer to overwritten helper methods and to abstract ones that are not overwritten.
Note that HTML file for new template is not necessary as we refer to abstract one all the time.
Source code is available on Github here!