backbonejs view without a model - javascript

Can I have a view without a model?
I just want to render some data with the backbone view that I'm familiar with. The data doesn't map to a REST url or some model.
Can I do that or should I just make a model anyway?

You don't always need a model.
Models and views don't have to be 1:1. In fact, they probably rarely are in practice. Some views might render data for several different models. Others might not, and instead might listen for DOM events, or render data from a third-party source, or any number of other things that don't require a model.

Models and Views are not tied together. There are no dependencies between the other.
You don't have to have a model to make a view.
You can just make Backbone render your data using the backbone's view.

Related

creating new entities in Backbone Marionette for related models

I've built the backbone app with one model ("conference"). Now I added second model ("talk"). talks belongs to conference, conference has many talks. The nested json is created and it is easy to render it into single-conference template with .eco like this:
I can basically build nested json and render nested attributes, no problem but is it a good architecture? Later it will have more layers , every talk will have many comments. What I should do?
Should I build new entities "talks" and use Backbone - associations?
What is the right way to deal with models relations.
My code is based on backboneonrails tutorial and it is very structured: https://github.com/lipenco/talkingheads
I want to maintain good architecture while going into related models.
It's not good to store objects in model's attribute. You can have problems with 'change' event not triggered if you change value of properties in attribute that is object.
So I think it's better to create separate model for talk. You can do all association work manually or use library for that: http://backbonerelational.org/

durandal.js viewmodel communication

Does anyone know what's the easiest way to get an instance of a view model within another view model. To be more specific, i would like to load the instance of one view model into another view model so that the latter can call methods of the former.
Does durandal keep a list of all view models that were used during the composition?
I guess one way to deal with that is applying the pub/sub pattern which is supported by durandal.
Another way would probably be to manually get the view model with the aid of knockout and the dataFor utility function.
However, i would like to know if there is a way to explicitly get the instance of a composed view model.
Note: my modules expose a constructor rather that singleton object
You can do it just by using RequireJS to bring in the viewmodel like you would another module/viewmodel. But you really want to avoid this for viewmodel communication and go with events instead.
A viewmodel will publish an event through the event aggregator and the other viewmodel is then subscribing to that event.
Check out the “Using Application-Wide Messaging” section here.

Backbone - shared model

I started reading some Backbone tutorials and I found one thing that astonishes me. Why models are created inside of view? What if I want two different views for one model (what I think MVC is for)? Let's say I need a model Colors, DisplayView view which displays them and ControlsView which allows me to set their configuration. How to handle this?
Backbone does not require that you create your models inside your views - you can (and often should) create your models independently of your views so that they can be shared. Also, just because you create a model inside a view doesn't mean you can't pass a reference to that model to another view and share it that way.
Most likely the tutorials you are reading are very simple and create single models for single views to make the tutorial easier to follow.

Backbone: Are Views really Controllers?

I'm building my first Backbone.js app and I'm confused about how much responsibility I'm supposed to give to or hide from my Views.
In my example, I'm building a Rich UI Table (similar to YUI's datagrid) that's dynamically generated from a Collection. In my app I call this an "AppTable". In my understanding of MVC, I would imagine that there'd be some kind of AppTable controller which finds the correct Collection, grabs a "dumb" View and passes to the View whatever information from the Collection it needs to render. In this senario, the View would do little more than take the data provided to it and modify the DOM accordingly, maybe even populating a template or attaching event listeners.
Backbone seems to do away with the idea of having a controller mediate between the View and Collection. Instead a View gets initialized with a reference to a Collection and it is View's responsibility to update itself.
Am I understanding this architecture correctly?
Assuming I do, my question then becomes, what happens when my View needs to do more and more? For example, I want column sorting, drag-and-drop for rows, pagination, searching, table control links (like new, copy, delete row... etc), and more. If we stick with a "smart" View paradigm where the View is connected directly to a Collection, do the above functions become attached to View object?
Thinking through this, I could see the View growing from a simple table wrapper to pretty messy beast with lot of functionality attached to it. So, is the View really a controller in this case?
Your understanding of the architecture is correct. Backbone does not recognize the concept of a "controller" in the traditional MVC sense. (In fact, Backbone used to actually have an object called a Controller, but it has been renamed Router to more accurately describe what it does.)
The functions you list (drag-drop, delete rows, sorting, etc.) would all belong in a View. A view describes what you see and responds to user input. Anything involving an event (a click, a keypress, a submit, etc.) all go inside of a view. But your view should never actually manipulate the data; that should be done by its model. You are correct in thinking that a view acts like a controller, because it packages data and sends it to the model, which will then validate/set/save appropriately. Once those actions have occurred, the view re-renders itself to represent the new version of the data inside the model.
One note of caution: your view should not be too strenuously tied to the DOM. It is Backbone convention to have a top-level DOM element that your view is tied to (e.g., a form or a div) and then deal only with its sub-elements. That is appropriate; in general, things like "remove this link from this div" inside your view are not. If you find your view growing unwieldy, you most likely need to break it into subviews, each with their respective behaviors as components of their whole.
My thoughts on this updated below:
I think Josh gave a good answer, however, in my experience, building a few Backbone apps, even medium-complexity apps do need a separate controller class.
To clarify what I mean about a controller: The functionality between the model (or router) and the view that creates and instantiates the new view class and kills (and unregisters events) on the old one. This functionality might be the same for many views (so a direct one-to-one relationship between views and controllers probably isn't needed) but sometimes one needs to pass in a model or other additional extra values.
Right now, I just have one controller with a few if statements for adding some unique data to certain views for most apps I've built but I'm looking at setting up an architecture where it will check to see if a unique controller exists for that view else it falls back to the standard controller. Nothing special, but should do the job.
Update: After six months of building Backbone apps I realized that routers can be split up and extended just like views. (duh?)
Right off the bat, I knew to make a base view of functionality I know that all my views would need. Similarly, I would make base views for each section, like "profile" pages or "inbox" pages that I know would all use the same functionality. This wasn't so clear to me in the beginning with routers, but the previous name of "Controller" hinted at this.
Most people (as in every example of Backbone I've ever seen on the web) just use one monolithic router instantiation to handle all routes but you can actually have 1-to-1 parity of routers to views, or in my case, a base router for checking user auth and such and then one for each major section. That way if you need to pass in certain models or collections to a router on page load, you don't need to add code to one monolithic router, but instead pull up the unique router for that view. I find this is currently better than creating a separate controller class. The base router can be in charge of last instantiated view, etc, so you can kill the last view before instantiating the new one.
TLDR: Use multiple Routers as controllers. I believe that's what they were meant for and it works well.
I've struggled with the same semantic issues when trying to map out a single-page app. In the end I decided that Backbone is using the wrong name.
When you look at a Backbone app in the browser, the View is not actually a view at all, its el member is the view. Backbone.View is either a view controller or, probably more correctly, a presenter.
Some supporting evidence:
you never see a Backbone.View on the screen, its always the el or $el that is applied to the DOM
a Backbone.View does not receive user input, the DOM element receives input and the events are delegated via the events hash of the "view"
a BackBone.View manages model or collection changes and translates these changes to dumb-view (DOM) elements, then applies them to the actual view, e.g. this.$el.append('<p>Cats!')
I think Backbone.Presenter would be a better name, but I can also see the historical issues with there being a former Backbone.Controller and the amount of work renaming introduces.
I have settled on the following structure for my latest project:
an app controller, extended from Backbone.View, tied to the body element
several model collections to cache data retrieved from the server
a Backbone.Router that translates route changes into Backbone events and triggers them on itself
many app controller methods that handle the router events the app controller listens to
an app controller method prepares any needed models, then initiates a presenter (extended from Backbone.View) and attaches it to the body element
All these parts are initiated and owned by the app controller. The presenters do not know why or where they are on the page and only care for their own DOM elements and the changes they receive from this.model.
Have a look at this part of backbone documentation
http://documentcloud.github.com/backbone/#FAQ-tim-toady
References between Models and Views can be handled several ways. Some
people like to have direct pointers, where views correspond 1:1 with
models (model.view and view.model). Others prefer to have intermediate
"controller" objects that orchestrate the creation and organization of
views into a hierarchy. Others still prefer the evented approach, and
always fire events instead of calling methods directly. All of these
styles work well.
So, backbone does not take that decision for you.
I have a very similar use case (table grid with pagination, ordering, live filtering, and forms with client-side validation, master-details relations, etc.)
In my case, I first started with a Router behaving just like a controller, and quite quickly my code got a bit messy.
So I completely removed Routers (I'll add them back later, but just as an addition) and created my own controller (that in fact works as a presenter). It's just a javascript class, with Backbone.extend backed in to handle inheritance.
The idea is that the view recieves all the data it needs to display itself (model, collection, and the el in which it should be parsed), set up listener on dom events, and then executes controller methods. It never directly modifies the data nor it interacts with other views, it tells the controller to do it.
A view can have subviews, and in that case the subview only interacts with the parent view, or directly with the controller.
So far now it seems to work, but anyway things are not so simple as I expected them to be...
I hope to publish it in the next few days.
A different perspective from the other answers here is that, just because you are using the Backbone framework, that doesn't mean that your entire codebase must be wrapped in Backbone classes.
Personally, my controller is an amalgamation of "raw" Javascript and Backbone routes, and I never use Views for control logic at all. IMHO views are for ... well, view logic, and specifically for wrapping elements. If you're using a view for anything that doesn't directly connect to an HTML element you are (again, IMHO) doing something wrong.
Backbone is awesome, but that doesn't mean that it's a silver bullet that can be applied to everything.

Am I deviating from MVC if I have a Backbone View without a Model?

I have a couple of Views which do not seem to have logically coherent Models. I can still try to create dummy Models for these (and properly have routers as well) but it seems unnatural to me.
So is having a Backbone View without a corresponding Model an anti-pattern?
What do the experts say on this?
the various components of backbone play well with each other, but there's no need for them to always go together.
i very regularly have models with no views, and views with no models. each of the pieces of a backbone app can be used in many different ways to facilitate what you need your app to do.
I don't think it is specifically an anti-pattern. If all you are trying to do is encapsulate view behavior, it might make sense to write a view and attach it to an element. It might not have any business logic or persistable data... it might just be a View that encapsulates view behavior (like something that manages the state of an element based on events). In that case, there is no need for a model.
On the other hand, if you are managing a bunch of variables (persistable or not) and any type of business logic, then it makes sense to break that out into a model.
If you are considering adding a dummy model or any other logic/code to make the architecture fit a pattern, that should be a red herring. The pattern should be there to assist you in designing logically well organized predictable code.

Categories

Resources