Search code examples
javascriptvariablesmeteorhelpermeteor-blaze

How to declare a variable only one time in JavaScript helpers?


I am developing web components with meteor-blaze.

In Template helpers,

Template.Button.helpers({
btnName: function() {
    var FirstBtn = new ButtonComponents('Name', this.class, '50px', '30px', '#DDDDDD');
    return FirstBtn.buttonName();
},
btnClass: function() {
    var FirstBtn = new ButtonComponents('Name', this.class, '50px', '30px', '#DDDDDD');
    return FirstBtn.buttonClass();
},
btnStyle: function() {
    var FirstBtn = new ButtonComponents('Name', this.class, '50px', '30px', '#DDDDDD');
    return FirstBtn.buttonStyle();
}});

I want to declare FirstBtn only one time in helpers.

I don't want to declare FirstBtn outside of helpers because of this.class.

How can I do this?


Solution

  • var FirstBtn;
    function getFirstBtn(cls) {
        if (FirstBtn == null) {
            FirstBtn = new ButtonComponents('Name', cls, '50px', '30px', '#DDDDDD');
        }
        return FirstBtn;
    }
    
    Template.Button.helpers({
        btnName: function() {
            return getFirstBtn(this.class).buttonName();
        },
        btnClass: function() {
            return getFirstBtn(this.class).buttonClass();
        },
        btnStyle: function() {
            return getFirstBtn(this.class).buttonStyle();
        }
    });
    

    Added: I'd strongly recommend you to create this button in the onCreated and store it in the template instance itself. You can later refer to it from helpers like this: Template.instance().FirstBtn.buttonName() for example.