gpt4 book ai didi

javascript - View 之间的backbone.js事件

转载 作者:行者123 更新时间:2023-12-02 17:36:07 26 4
gpt4 key购买 nike

我在 Backbone.js 中有两个 View ,每个 View 都有自己的 html 选择元素。在第一个列表选择事件上,我希望触发一个事件,提醒第二个 View (选择元素)接收事件并触发更新。

我的问题是在初始选择更改时调用方法并引发事件,尽管第二个 View 从未注册它。

 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");
},....

第二个 View 监听“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
});
},

任何有关如何在 View 之间正确设置触发器的帮助都会很棒!干杯

最佳答案

在您的第一个 View 中,ClubSelectView在这一行:

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

“这个”指的是ClubSelectView 。然而,在你的第二个观点中:

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

“这个”指的是MatchSelectView 。这意味着它正在监听自身的“teamSelect:change”事件。但该事件并不是针对其本身,而是针对第一视角。这是Marionette的主要问题之一。 - Backbone 插件 - 旨在解决这个问题。它提供了一个对于整个应用程序来说是全局的事件聚合器。所有 View 都可以监听聚合器上的事件并响应它们。在当前设置中,您必须从第一个 View ClubSelectView 获取对第二个 View 的引用。然后在该对象上触发事件,而不是在 this 上触发事件.

关于javascript - View 之间的backbone.js事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com