Skip to content

Instantly share code, notes, and snippets.

@josephmisiti
Created July 19, 2012 21:18
Show Gist options
  • Save josephmisiti/3146871 to your computer and use it in GitHub Desktop.
Save josephmisiti/3146871 to your computer and use it in GitHub Desktop.
// create pub-sub functionality
Backbone.pubSub = _.extend({}, Backbone.Events);
// view one needs to trigger an event in view2
View1 = Backbone.View.extend({
triggerView2Event : function() {
Backbone.pubSub.trigger('view2event', { 'some' : 'data' } );
})
})
// view two which changes based on the view2event
View2 = Backbone.View.extend({
initialize: function() {
Backbone.pubSub.on('view2event', this.onChange, this);
},
onChange : function() {
// update the view
}
})
@piatra
Copy link

piatra commented Feb 11, 2014

Thanks for the tip! Helpful :)

@gunalmel
Copy link

Here is my case with a similar need: Backbone listenTo seemed like a solution to redirect to login page for timed out or not authenticated requests.

I added event handler to my router and made it listen to the global event such as:

    Backbone.Router.extend({
        onNotAuthenticated:function(errMsg){
            var redirectView = new LoginView();
            redirectView.displayMessage(errMsg);
            this.loadView(redirectView);
        },
        initialize:function(){
            this.listenTo(Backbone,'auth:not-authenticated',this.onNotAuthenticated);  
        },
        .....
    });

and in my jquery ajax error handler:

    $(document).ajaxError(
        function(event, jqxhr, settings, thrownError){
            .......
            if(httpErrorHeaderValue==="some-value"){
                 Backbone.trigger("auth:not-authenticated",errMsg);
            }
        }); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment