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

后端 未结 2 1502
鱼传尺愫
鱼传尺愫 2021-01-03 07:38

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

相关标签:
2条回答
  • 2021-01-03 08:14

    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, ...);
    
    0 讨论(0)
  • 2021-01-03 08:21

    The best way I have seen is in the method proposed by Derick Bailey. In short you can create an event aggregator, which provides a centralized object for raising events to which different views can subscribe. The beauty of this solution is that it is very simple to implement as it makes use of Backbone's existing event system.

    0 讨论(0)
提交回复
热议问题