'Backbone and jQuery trigger / bind custom event not heard
I'm writing a backbone app within an ASP.NET MVC page, and I'm having a truly baffling (to me) problem with using two custom events.
So, the MVC View (Planning.cshtml) has a select control which triggers the Backbone router to fetch a model on change. This model takes a good 10 seconds or so to load, so I want to disable the select while it loads to prevent multiple requests. To do this, I'm having my router trigger two custom events: 'subview-loading' and 'subview-loading-complete', and having my MVC view listen for these events.
The problem I'm having is that the router can hear both events, but Planning.cshtml will only hear the 'subview-loading-complete' event, not the first event.
Planning.cshtml code:
$(document).ready(function () {
var router = new Router({
el: '#TermPlanningReport'
});
var $routerEl = $(router.el);
$routerEl.bind('subview-loading', function() {
console.log('Planning.cshtml heard subview-loading');
//disable control
});
$routerEl.bind('subview-loading-complete', function() {
console.log('Planning.cshtml heard subview-loading-complete');
//enable control
});
});
Router.viewTerm() - the route method loading the model:
viewTerm: function (term) {
var that = this,
termModel = new PlanningTerm({ term: term }),
$thisEl = $(that.el);
//for testing purposes, see if router can hear itself...
$thisEl.on('subview-loading', function() {
console.log('router heard subview-loading');
});
$thisEl.on('subview-loading-complete', function () {
console.log('router heard subview-loading-complete');
});
//trigger loading
$thisEl.trigger('subview-loading');
// fetch data for model
termModel.fetch({
success: function (model, response, options) {
$thisEl.trigger('subview-loading-complete');
//render a vew...
},
error: function (model, response, options) {
$thisEl.trigger('subview-loading-complete');
//render a view...
}
});
},
Finally, my console output:
router heard subview-loading
router heard subview-loading-complete
Planning.cshtml heard subview-loading-complete
The variables $routerEl and $thisEl are both returning the same element properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
