2

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?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
HyeonggeunYun
  • 21
  • 1
  • 3
  • Why does `this.class` prevent you from declaring `FirstBtn` in the outer scope? – 4castle Aug 11 '17 at 07:15
  • It may be related to self referencing object https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations – brk Aug 11 '17 at 07:19
  • Because I use Inclusion tag(partial) with data context. `{{> Button class="btn black"}}` – HyeonggeunYun Aug 11 '17 at 07:19

2 Answers2

4
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.

Styx
  • 9,863
  • 8
  • 43
  • 53
0

You should put your variable in the Template instance, and access it with Template.instance().

Template.Button.onCreated(function(){
    this.FirstBtn = new ButtonComponents('Name', this.data.class, '50px', '30px', '#DDDDDD');
});

Template.Button.helpers({
btnName: function() {
    const instance = Template.instance();

    return instance.FirstBtn.buttonName();
},
btnClass: function() {
    const instance = Template.instance();

    return instance.FirstBtn.buttonClass();
},
btnStyle: function() {
    const instance = Template.instance();

    return instance.FirstBtn.buttonStyle();
}});

Writing const instance = Template.instance(); at the first line of your helper is a good practice recommended by the BlazeJS documentation.

Gaëtan Rouziès
  • 490
  • 1
  • 3
  • 16