LoginSignup
2
2

More than 5 years have passed since last update.

helper内でのプロパティー定義

Last updated at Posted at 2014-12-22

ドキュメントによると、Lightningでは、コントローラー内からコントローラー内の別のメソッドを呼ぶ代わりに、ヘルパー関数を呼ぶことが推奨されています。ヘルパー関数から別のヘルパー関数を呼ぶのはthisオブジェクトを使えば問題なくできます。

ヘルパーオブジェクトには、関数以外のプロパティーも定義することができます。(コントローラーでは関数しか定義できません。レンダラーでもプロパティーは定義できるようです。)

ComponentHelper.js
({
    b : false,
    num : 3,
    str : '"data"',
    s : {str : "data"},
    getConstStr : function(){ return 'const'; },
    test : function() {
        console.log(this.b);
        this.b = true;
        console.log(this.b);
        console.log(this.str);
    }
})

しかしながら、正規表現リテラル(/re/)やオブジェクトのnew、あるいは関数の実行結果などを割り当てようとすると保存時にエラーになりますし、"で括られていない文字列を定義するとなぜか実行時エラーになります。

false||data
Uncaught ReferenceError: data is not defined

定数文字列などを簡単に定義したい場合には、上記のように一段オブジェクトの中にしまうか、文字列を返す関数を用意すると良いです。より複雑なことをやりたい場合はアクセス用の関数を用意するという方法もあるかもしれません。

ComponentHelper.js
({
    props : null,
    setProp : function(name, value){
        if (!this.props)
            this.initProps();
        this.props[name] = value;
    },
    getProp : function(name) {
        if (!this.props)
            this.initProps();
        return this.props[name]; 
    },
    initProps : function(){
        this.props = {d: new Date(), re: new RegExp(), o: {}};
    },

    testProps : function(){
        console.log(this.getProp('d'));
        this.setProp('a', new Date());
        console.log(this.getProp('a'));
    }
})

しかしながら、ここまでやるなら、AuraStorageServiceを使うのが本筋と思われます。AuraStorageServiceについては別記事でご紹介しています。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2