Reputation: 197
My Backbone.View looks this way:
define(["promise!table_config", "BBModel"], function (config, myModel) {
"use strict";
return Backbone.View.extend({
initialize: function () {
this.model = new myModel({
foo: config
});
...
},
render: function () {
...
}
});
});
Is is a good or bad practice to initialise a model inside a view? Particularly in this case, in a require.js module where 'config' is a require-promise, motivating me to put put a model inside a view.
Upvotes: 2
Views: 334
Reputation: 35790
While Backbone does have a Model
and a View
class, it is not a strict MVC framework (eg. it lacks a Controller
class). The Backbone documentation page explains as much (emphasis mine):
How does Backbone relate to "traditional" MVC?
Different implementations of the Model-View-Controller pattern tend to disagree about the definition of a controller. If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view. We call it a View because it represents a logical chunk of UI, responsible for the contents of a single DOM element.
Given that, even though (as @Evgenly mentioned in the comments) "its not view responsibility to instance model, its controllers task" ... since the Backbone View
is (conceptually) a controller, it absolutely makes sense to create your models inside your views.
But putting that theory aside, here's a more practical answer. I work on a 3+ year-old Backbone app, along with two other developers (and more previously). In that app the vast majority of all models get created inside views (the few remaining ones get created inside routes). Not only has this not been a problem for us, but I can't even imagine any other way of doing it.
Upvotes: 2