[英]backbone.js events between views
我在Backbone.js中有兩個視圖,每個視圖都有自己的html select元素。 在第一個列表選擇事件中,我希望觸發一個事件,該事件警告第二個視圖(選擇元素)以接收事件並觸發更新。
我的問題是初始選擇更改方法被調用和事件引發雖然第二個視圖從未注冊它。
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");
},....
第二個視圖聽“teamSelect:change”觸發器
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
});
},
任何有關如何在視圖之間正確設置觸發器的幫助都會很棒! 干杯
在您的第一個視圖中, ClubSelectView
就在這一行:
this.trigger("teamSelect:change", "Team selected from dropdown items");
“this”指的是ClubSelectView
。 但是,在您的第二個視圖中:
this.on("teamSelect:change", function (msg) {
alert("teamSelect:change " + msg); //never triggered
});
“this”指的是MatchSelectView
。 這意味着它正在監聽事件“teamSelect:change”。 但事件本身並沒有被解雇,而是第一種觀點。 這是Marionette (Backbone插件)的主要問題之一。 它提供了一個Event Aggregator,它對您的整個應用程序是全局的。 所有視圖都可以偵聽聚合器上的事件並對其進行響應。 在當前的設置中,您必須從第一個視圖ClubSelectView
獲取對第二個視圖的引用,然后在該對象上觸發事件,而不是在this
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.