如何使用 Backbone js 中的函数从一个视图调用另一个视图

How to call another View from a view using a function in Backbone js

是否有下划线或 backbone 函数可用于从另一个视图调用视图?我只想使用历史视图显示信息,但调用它时遇到问题。

var CityModel = Backbone.Model.extend({
defaults: {
    city: null,
    nickName: null,
    founded: null
}
});
var StudentCollection = Backbone.Collection.extend({
   Model: CityModel
});

// This outputs the data when there is a click event
var History = Backbone.View.extend({
    tagName: 'li',
    template: _.template("<h2><%= city %></h2>"),
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html(this.template(this.model));
        $('.History').append(this.$el);
        return this;
    }
});

我想从我命名为 displayFunction 的 CityView 函数点击事件调用历史视图

var myCityTemplate = '<h1 class= "displayInfo" name= "showCity"><%= city %></h1>';
var CityView = Backbone.View.extend({
    tagName: "li",
    template: _.template(myCityTemplate),
    initialize: function(){
        this.listenTo(this.model, 'change', this.render);
    },
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },
    events:{
        'click .displayInfo':'displayFunction'
    },
    displayFunction: function(){
        // This is to find where city lives, check out the console.log without the innerHTML
        // console.log(this.$el.find('h1[name= "showCity"]')[0].innerHTML);
        CityName = this.$el.find('h1[name= "showCity"]')[0].innerHTML;
        console.log(Cities.where({city: CityName}));
        var myCity = Cities.where({city: CityName});
        var CityHistory = new History({model: myCity});
    }
});

我使用模型 mycity 调用历史视图,这是我在从点击事件中获取数据后定义的。我 console.log 城市时确实有数据。

var CityListView = Backbone.View.extend({
    el: ".cities",
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.empty();
        this.collection.each(function(places){
            var MetropolisViewModel = new CityView({model: places});
            this.$el.append(MetropolisViewModel.render().$el);
        }, this);
    }
});
var city1 = new CityModel({city: "Anaheim", nickName: "Disney", founded: "1840"});
var city2 = new CityModel({city: "Las Vegas", nickName: "Sinners",   founded: "1889"});
var city3 = new CityModel({city: "New York", nickName: "City of hope", founded: "1750"});
var city4 = new CityModel({city: "Palm Springs", nickName: "Very hot", founded: "1849"});
var Cities = new StudentCollection([city1, city2, city3, city4]);
var myCityList = new CityListView({collection: Cities});

一切正常,唯一的问题是从 cityView 调用历史视图似乎不起作用。我的目标是使用历史视图作为仅向我的 HTML.

显示每个城市的数据的一种方式

我弄明白了,问题是当我使用

this.$el.html(this.template(this.model)

在历史视图中,我将要显示的数据与从我使用的 CityView 中显示的数据相比采用不同的格式

this.$el.html(this.template(this.model.toJSON()));

显示数据。所以问题不在于调用视图,而在于以不同方式显示数据。不同是因为当我从模型中获取信息时,格式差异足以导致显示该数据时出现问题。因此,我使用了 this.$el.html(this.template(this.model[0].attributes));在我的历史视图中正确输出数据。