3
votes

I thought this to be an easy thing but I am stuck. Here is the code:

On Server:

app.get('/api/currentuser',function(req,res){
  User.findOne({ _id: req.currentUser.id },'name',function(err, user_details) {
        if (err) {
            return next(err);
        }
        if (user_details) {
            res.send(user_details);
        } else {
            return next(new NotFound('Could not find any such user'));
        }
    });
});

where req.currentUser.id is the id of logged in user from session. So if call /api/currentuser method, I am getting a response

{
 _id: 6161616161619hjksk
 name: 'Devesh Kumar'
}

Now in Backbone Marionette I am using a Model and an Item View to show the user name (and his _id and other details may be)

Backbone :

var CurrentUser = Backbone.Model.extend({urlRoot: '/api/currentuser' });

var CurrentUserView = Marionette.ItemView.extend({
    template: "#current-user-view"
});

var currentuser = new CurrentUser();

var currentuser_view = new CurrentUserView({
    collection: currentuserdetails
});

Completepp.rightRegion.show(currentuser_view);

Template:

<%= name %> 

However, there is an error. It says name is not defined. When I set a CollectionView, and an ItemView then it can properly render. But in my case its not needed to set a collection

As a general question, how do I render such application level views in Backbone? Please Help

1

1 Answers

7
votes

Since the url will be the same for each current user instance, try using this definition:

var CurrentUser = Backbone.Model.extend({url: '/api/currentuser' });

url will simply return the provided string, whereas urlRoot will attempt to generate the proper full url with the user id.

Then, you should be able to have:

var currentuser = new CurrentUser();

currentUser.fetch();

var currentuser_view = new CurrentUserView({
    collection: currentUser
});

Of course, you need to make sure the user information has been fetched from the server before rendering the view, or you'll get the "name is not defined" error. You can see how to synchronize your code so the view waits for the data before rendering in this blog post: http://davidsulc.com/blog/2013/04/01/using-jquery-promises-to-render-backbone-views-after-fetching-data/