私はMeteorで継承を使用したいと考えていましたが、ドキュメントやスタックオーバーフローで何も見つかりませんでした。meteor.jsでの継承の使用
テンプレートに別の抽象テンプレートまたはクラスのプロパティとメソッドを継承させることはできますか?
私はMeteorで継承を使用したいと考えていましたが、ドキュメントやスタックオーバーフローで何も見つかりませんでした。meteor.jsでの継承の使用
テンプレートに別の抽象テンプレートまたはクラスのプロパティとメソッドを継承させることはできますか?
私は短い答えはノーであるが、ここで長い答えはだと思う:私はテンプレート間で機能を共有するためにやった
ことの一つは、ヘルパーのオブジェクトを定義して、複数のテンプレートに割り当て、同様にすることですso:
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;});
は、私はこの質問hereに答えました。このソリューションではinheritance
は使用されませんが、簡単にテンプレート間でイベントやヘルパーを共有できます。
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
詳細については
および例は、私のother answerを参照してください。一言で言えば
は、私はテンプレートを取り込みextendTemplate
機能や引数としてヘルパーやイベントを持つオブジェクトを定義します。
OOPでは、 "継承を超えた合成"を使用することをお勧めします。この回答は前者に有利です。 –
最近、私は自分のアプリで同じ機能が必要でしたので、私は自分のパッケージを作成して、そのままの状態で仕事をすることにしました。それはまだ進行中ですが、あなたはそれを行かせることができます。
次のように基本的には、全体の方法は次のとおりです。
あなたは抽象的なものを拡張したいあなたの新しいテンプレート(new_template.js)で// 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;
};
、次のように書きます。
今// this copies your abstract template to your new one
Template.<your_abstract_template_name>.copyAs('<your_new_template_name>');
あなたは次のようにして、ヘルパーやイベント(私の場合はphotos
ヘルパー)を上書きすることができます:
あなたは上書きされたヘルパーメソッドを参照し、上書きされないメソッドを抽象化します。
新しいテンプレート用のHTMLファイルは、抽象的なものを常に参照するので必要ありません。
ソースコードはGithub hereで入手可能です!
私は流星のために 'view'という[パッケージ](https://atmosphere.meteor.com/package/view)を作成しました。私はビュークラスのようなバックボーンで流星の景色を包むためにそれを使用します。たぶんそこで始まるいくつかのアイデアが見つかるでしょう。 – Andreas