Backbone JS: can one view trigger updates in other views?

前端 未结 7 1224
失恋的感觉
失恋的感觉 2020-12-23 02:20

In my simple project I have 2 views - a line item view (Brand) and App. I have attached function that allows selecting multiple items:

var BrandView = Backbone.V         


        
7条回答
  •  情深已故
    2020-12-23 03:09

    I use what Addy Osmani calls the mediator pattern http://addyosmani.com/largescalejavascript/#mediatorpattern. The whole article is well worth a read.

    Basically it is an event manager that allows you to subscribe to and publish events. So your AppView would subscript to an event, i.e. 'selected'. Then the BrandView would publish the 'selected' event.

    The reason I like this is it allows you to send events between views, without the views being directly bound together.

    For Example

    var mediator = new Mediator(); //LOOK AT THE LINK FOR IMPLEMENTATION
    
    var BrandView = Backbone.View.extend({
        toggle_select: function() {
            ...
            mediator.publish('selected', any, data, you, want);
            return this;
        }
    });
    
    var AppView = Backbone.View.extend({
        initialize: function() {
            mediator.subscribe('selected', this.delete_selected)
        },
    
        delete_selected: function(any, data, you, want) {
            ... do something ...
        },
    });
    

    This way your app view doesn't care if it is a BrandView or FooView that publishes the 'selected' event, only that the event occured. As a result, I find it a maintainable way to manage events between parts of you application, not just views.

    If you read further about the 'Facade', you can create a nice permissions structure. This would allow you to say only an 'AppView' can subscribe to my 'selected' event. I find this helpful as it makes it very clear where the events are being used.

提交回复
热议问题