George Reith
George Reith

Reputation: 13476

Backbone.js get previous view from collection

Now I understand this could be achieved by referencing a view from it's model. However I am attempting to stick with the "best practices" for Backbone.js where that is considered poor practice as model -> view can often be a one to many relationship.

The problem I have is this (The code samples are to help you visualise the problem):

I have an array of grouped views. Each grouped array of views contains views from multiple collections. e.g.,

var views; // Assume views is pre-populated with an array of views, each view's model may be stored in a different collection.

var viewGroups = _.groupBy(views, function(view) {
    return view.model.attributes.timestamp; // Unix timestamp for example
});

As I loop through the grouped views I need to access the views of the model that comes directly before each view's model in it's collection.

I am able to access the previous model in the collection like so:

_.each(viewGroups, function(viewGroup) {
    _.each(viewGroup, function (view) {
        var model = view.model;
        var collection = model.collection;
        var previousModel = collection.at(collection.indexOf(model) - 1);
    });
});

But because there is no affiliation from the model to it's views I am unable to find out which views subscribe to the previous model in the collection.

var previousModelsViews = ???

How would I do this following the design pattern that models are ignorant of views.

Upvotes: 0

Views: 673

Answers (1)

Daniel Aranda
Daniel Aranda

Reputation: 6552

You do not need to know the view. Just add a custom event listener in the views:

View:

initialize : function(){
  this.model.on('customAction', this.customAction);
},
customAction : function(){
   //here you could do the DOM manipulation that you need on your previous view
}

And on your code add this:

var previousModel = collection.at(collection.indexOf(model) - 1);
previousModel.trigger('customAction');

Update: after you updated your requirement: I still thinking that everything could be with events, just in the previous view dispatch other event:

View:

initialize : function(){
  this.model.on('customAction', this.customAction);
  this.model.on('PreviousWindowSize', this.previousSizeReceived);
},
//Previews View will arrive here 
customAction : function(nextModel){
   nextModel.trigger('PreviousWindowSize', {width: this.$el.width()});
},
//Current View will receive the size of the previous View here
previousSizeReceived : function(size){
   console.log(size);
}

And on your code add this(check that I added the previous model in the trigger):

var previousModel = collection.at(collection.indexOf(model) - 1);
previousModel.trigger('customAction', previousModel);

Upvotes: 1

Related Questions