从另一个视图调用视图函数 - Backbone

Ale*_*and 8 backbone.js

我的申请中有以下观点.基本上我想在点击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');
   }
});
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 14

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

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

然后,您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);
    },
    //...
});
Run Code Online (Sandbox Code Playgroud)

然后你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'));
    },
    //...
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/sXFLC/1/

您可能希望current_house成为一个真正的模型,而不仅仅是id当然,但这很容易.

app_state一旦你拥有它,你可能会找到各种其他用途.您甚至可以免费添加一些REST和AJAX并为您的应用程序设置获得持久性.

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