Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make one view aware of another's changes?

Tags:

backbone.js

Suppose you are making a music library app.

You have one view with a list on genres and another that shows the contents of the selected genre. When the user clicks a genre on the list, the contents in the other view should be updated accordingly.

What is the best way to do this so that there are minimal dependencies?

I have not found any other place to listen to the mouse clicks than the view that draws the individual genre. I can send an event from there, but what is the optimal way of getting that event to update the other view which draws the genre contents? Who should listen to that event, the genre content view or its collection?

EDIT: I instantiate both views from the router of the app and I did manage to get this to work by making the views aware of each other, but that's not optimal of course.

like image 385
wannabeartist Avatar asked Dec 06 '22 14:12

wannabeartist


1 Answers

You could make a simple model to hold the application state, you don't need anything fancy, just a bag of data that implements the usual Backbone event methods:

var AppState  = Backbone.Model.extend({});
var app_state = new AppState();

Then the genre list view would listen for click events (as you already have) and set the current genre on the app-state model when someone changes it:

var Genres = Backbone.View.extend({
    //...
    choose: function(ev) {
        // This would be the click handler for the genre,
        // `.html()` is just for demonstration purposes, you'd
        // probably use a data attribute in real life.
        app_state.set({genre: $(ev.target).html() });
    },
});

The view for the individual genre would listen for "change:genre" events on the app-state model and react as the genre changes:

var Genre = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'change_genre');
        app_state.on('change:genre', this.change_genre);
    },
    //...
    change_genre: function() {
        // Refill the genre display...
    }
});

Demo: http://jsfiddle.net/ambiguous/mwBKm/1/

You can make models for any data you want and models are a convenient way of working with data events in Backbone. As an added bonus, this approach makes it fairly easy to persist your application's state: just add the usual Backbone persistence support to AppState and away you go.


If you only need a simple event bus to push non-data events around, you can use Backbone's Events methods to build a simple event aggregator:

app.events = _.extend({}, Backbone.Events);

Then, assuming you have a global app namespace, you can say things like this:

app.events.on('some-event', some_function);

and

app.events.trigger('some-event', arg1, arg2, ...);
like image 167
mu is too short Avatar answered Dec 26 '22 13:12

mu is too short