2013-05-07 6 views
5

BackboneJSを使用してサブビューからビュー関数を呼び出すことができるかどうかを知りたいと思います。 はいの場合、どのように動作していますか?BackboneJSでサブビューからビュー関数を呼び出す

サブビューからmainViewに属する関数 "hello"を呼び出したいとします。イベントがトリガたぶん場合

...

例:

var MainView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $(template); 
     this.subview = new SubView();    
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     var element = this.$template.attr('id'); 
     this.subview.setElement('#'+element).render(); 
    }, 

    hello: function() { 
     alert('Hello'); 
    } 

}); 


var SubView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $(template);   
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     //Call view function ' hello ' 
     //parentView.hello(); 
    } 

}); 

ありがとう!

+0

'MainView'を' var SubView = Backbone.MainView.extend'で拡張しようとしましたか?そうすれば 'SubView'の中から' hello'関数を呼び出すことができます。 –

答えて

8

あなたのサブビューにあなたの親ビューからの参照を渡すことができます。

http://jsfiddle.net/puleos/hecNz/

var MainView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $("<span>foo</span>"); 
     this.subview = new SubView({parent: this});    
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     var element = this.$template.attr('id'); 
     this.subview.setElement('#'+element).render(); 
    }, 

    hello: function() { 
     alert('Hello'); 
    } 

}); 


var SubView = Backbone.View.extend({ 

    initialize: function(options) { 
     this.$template = $("<span>bar</span>"); 
     this.parent = options.parent; 
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     this.parent.hello(); 
    } 

}); 

var mainView = new MainView(); 

console.log(mainView); 
2

あなたはこのようMainViewを拡張しようとすることができ:それ、その後すべき

var SubView = MainView.extend({ });

MainView内のhello機能への参照を指定してください。

あるいは、SubViewで、あなたのrender機能にこれを追加します。

MainView.prototype.hello.call(this) 

SubViewインスタンスのコンテキスト(テンプレート、他のVARS、など)を使用してMainViewhello関数を呼び出します。

+0

これは動作しますが、静的メソッドとしてhelloを呼び出しています。 SubViewを作成したMainViewインスタンスの状態にアクセスすることはできません。 –

+0

彼は親ビューの状態にもアクセスしたいですか? –

+2

少なくとも、リファレンス/オプションメソッドとスタティックコールのどちらを使うべきかは今では分かっています。 –

関連する問題