2012-06-14 11 views
8

私は自分のアプリケーションで次のビューを持っています。基本的には、App.HouseListElemViewのliをクリックするとApp.MapViewでshow_house()を呼びたいと思います。別のビューからビュー関数を呼び出す - バックボーン

これを行う最善の方法は何ですか?

App.HouseListElemView = Backbone.View.extend({ 
    tagName: 'li', 
    events: { 
     'click': function() { 
      // call show_house in App.MapView 
     } 
    }, 
    initialize: function() { 
     this.template = _.template($('#house-list-template').html()); 
     this.render(); 
    }, 
    render: function() { 
     var html = this.template({model: this.model.toJSON()}); 
     $(this.el).append(html); 
    }, 
}); 

App.MapView = Backbone.View.extend({ 
    el: '.map', 
    events: { 
     'list_house_click': 'show_house', 
    }, 
    initialize: function() { 
     this.map = new GMaps({ 
      div: this.el, 
      lat: -12.043333, 
      lng: -77.028333, 
     }); 
     App.houseCollection.bind('reset', this.populate_markers, this); 
    }, 
    populate_markers: function(collection) { 
     _.each(collection.models, function(house) { 
      var html = 'hello' 
      this.map.addMarker({ 
       lat: house.attributes.lat, 
       lng: house.attributes.lng, 
       infoWindow: { 
        content: html, 
       }     
      }); 
     }, this); 
    }, 
    show_house: function() { 
     console.log('show house'); 
    } 
}); 

答えて

14

現在の家はので、あなたのグローバルなアプリケーションの状態を保持するための新しいモデルを作成し、実際にアプリケーションのグローバル状態の一部です:その後、あなたHouseListElemViewapp_stateに値を設定することで、クリックに応答することができ

var AppState = Backbone.Model.extend({ /* maybe something in here, maybe not */ }); 
var app_state = new AppState; 

を:

App.HouseListElemView = Backbone.View.extend({ 
    //... 
    events: { 
     'click': 'set_current_house' 
    }, 
    set_current_house: function() { 
     // Presumably this view has a model that is the house in question... 
     app_state.set('current_house', this.model.id); 
    }, 
    //... 
}); 

してからMapViewは単にから'change:current_house'イベントを監視:

App.MapView = Backbone.View.extend({ 
    //... 
    initialize: function() { 
     _.bindAll(this, 'show_house'); 
     app_state.on('change:current_house', this.show_house); 
    }, 
    show_house: function(m) { 
     // 'm' is actually 'app_state' here so... 
     console.log('Current house is now ', m.get('current_house')); 
    }, 
    //... 
}); 

デモ:http://jsfiddle.net/ambiguous/sXFLC/1/

あなたはcurrent_houseは、実際のモデルではなく、もちろん単にidになりたいかもしれませんが、それは簡単です。

あなたが持っていればapp_stateのための多種多様な用途を見つけることができるでしょう。 RESTとAJAXを少し追加して、アプリケーション設定の永続性を無料で手に入れることもできます。

イベントは、バックボーンのあらゆる問題の通常の解決策であり、あなたが望むもののモデルを作ることができます。仮に、仮のモデルを厳密にまとめて接着することさえできます。

+0

美しい。ありがとう – AlexBrand

+0

+1。私の無知を許すが、この方法とappstateとの違いは何か[Backbone.Events](http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-学んだ/)伝統的なPubSub? – TYRONEMICHAEL

+1

@TyroneMichael:ほとんどの場合、簡単に永続化します。 PubSubは情報を経路指定するだけで忘れてしまうので、モデルは記憶しておき、サーバに状態を永続化させるのが簡単になります。 –

関連する問題