簡體   English   中英

在meteor.js中使用繼承

[英]Using inheritance in meteor.js

我一直希望在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

有關詳細信息和示例,請參閱我的其他答案

最近,我在我的應用程序中需要相同的功能,所以我決定創建我自己的包,將開箱即用。 雖然它仍在進行中,但你可以試一試。

基本上,整個方法如下:

// 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;
};

在您想要擴展抽象模板的新模板(new_template.js)中,寫下以下內容:

// this copies your abstract template to your new one
Template.<your_abstract_template_name>.copyAs('<your_new_template_name>');

現在,您可以通過執行以下操作,簡單地覆蓋您的幫助程序或事件(在我的情況下,它是photos幫助程序):

Template.<your_new_template_name>.photos = function () {
    return [];
};

您將引用覆蓋的輔助方法並抽象未覆蓋的方法。

請注意,新模板的HTML文件不是必需的,因為我們始終引用抽象的模板。

源代碼可以在Github上找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM