Reputation: 5460
I'm working on a BackboneJS application. One of the cases I'm working on, which seems to not want to fit into a MVC setup (or, more likely, my understanding of MVC doesn't cover where to put this) is the following.
I have a collection of models representing pictures. Let's say, for this example, 100 of them. I've got a controller that tells a view to load up with a selection of these models, as it shows the pictures page by page.. so page 1 shows the first ten, and etc.
The question here is whether or not the controller should be telling the view "Here are your models", or whether the view should know "I get my models from __ and I need to select a subset of them". The "and" is what worries me. The controller knows "the user has requested the first page of models", so it seems more natural to tell the view "here is the selection of models that the user has requested".
Is this the correct way of going about it?
Upvotes: 0
Views: 98
Reputation: 8189
Organizing your Backbone models might need to look like...
var Image = Backbone.Model.extend({
url: 'place/where/images/are'
});
var Images = Backbone.Collection.extend({
model: Image
});
var ImageView = Backbone.View.extend({
initialize: function(){
this.collection.bind('add', this.render, this);
this.collection.fetch({
data: {
// Send whatever you need to the server
}
});
},
render: function(model){
// do something with the added model
}
});
var myImageView = new ImageView();
This way your collection knows where to get the data, and the view makes the call to the server.
Upvotes: 0
Reputation: 782
I agree with Robert in that you're looking at it sort of the wrong way. You can only have one Model per View, so your Model should include all the pictures to be displayed in that View. For example, your Model could be:
public class Gallery
{
public List<string> ImageUrls { get; set; }
}
Now, your controller would pass a Gallery object to your View as its Model, and the View would them have all the image urls INSIDE the Model object. But the Model object is only one object within which all your images (and all other information for that view) should be contained.
You are right to want your controller to be the one deciding which images to display and SENDING them to the View. Usually, the rule of thumb is to have Models just be data structure, Views just be data display, and Controllers be the brain and where all the computations should be done. This is not necessarily universal at all, especially when you start dealing with outside services. But let's not digress.
I hope this helps, and that you're getting a better idea of how MVC websites are organized. Let me know if you have any more questions! :)
Upvotes: 2