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');
   }
});
4

1 回答 1

14

当前房屋实际上是您的应用程序全局状态的一部分,因此创建一个新模型来保存您的全局应用程序状态:

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

然后您HouseListElemView可以通过在 中设置一个值来响应点击app_state

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_state

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,并几乎免费获得应用程序设置的持久性。

事件是 Backbone 中每个问题的常用解决方案,你可以为任何你想要的东西制作模型,你甚至可以制作临时模型来严格地将东西粘合在一起。

于 2012-06-15T01:43:43.287 回答