Pergunta

I have two views in Backbone.js each to its own html select element. On the first list select event I wish to trigger an event that alerts the second view (select element) to recieve the event and trigger an update.

My issue is on the initial select change the method is called and event raised although the second view never registers it.

 define([
 'jquery',
 'underscore',
 'backbone',
 'models/user/UserModel',
 'collections/teams/TeamsCollection',
 'models/team/TeamModel'
 ], function ($, _, Backbone, UserModel, TeamsCollection, TeamModel) {

var ClubSelectView = Backbone.View.extend({
    el: "#clubList",
    events: {
        "select #clubList option": "optionSelected"
    },
    initialize: function () {
        var that = this;
        var user = UserModel;
        this.model = user;
        this.model.on('change', this.updateTeams, this);
        var teams = new TeamsCollection();
        this.collection = teams;
        this.createEasyDropDown();
    },
    optionSelected: function () {
        alert("optionSelected"); //this alert is called
        this.trigger("teamSelect:change", "Team selected from dropdown items");  
    },....

second view listening to "teamSelect:change" trigger

 define([
'jquery',
'underscore',
'backbone',
'models/user/UserModel',
'collections/matches/MatchesCollection',
'models/match/MatchModel'
], function ($, _, Backbone, UserModel, MatchesCollection, MatchModel) {
var MatchSelectView = Backbone.View.extend({
el: "#fixtureList",
events: {

},
initialize: function () {
    var that = this;
    var user = UserModel;
    var teams = new MatchesCollection();
    this.collection = teams;
    this.createEasyDropDown();
    this.on("teamSelect:change", function (msg) {
        alert("teamSelect:change " + msg); //never triggered
    });
},

Any assistance on how to correctly set the trigger between views would be great! Cheers

Foi útil?

Solução

In your first view, ClubSelectView on this line:

this.trigger("teamSelect:change", "Team selected from dropdown items");  

"this" refers to ClubSelectView. However, in your second view:

this.on("teamSelect:change", function (msg) {
    alert("teamSelect:change " + msg); //never triggered
});

The "this" refers to MatchSelectView. That means that it is listening for the event "teamSelect:change" on itself. But the event is not being fired on itself but on the first view. This is one of the main problems that Marionette - a plugin for Backbone - was meant to solve. It provides an Event Aggregator which is global to your entire application. All views can listen for events on the Aggregator and respond to them. In your current setup, you would have to get a reference to the second view from your first view ClubSelectView and then trigger the event on that object, not on this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top