Backbone.js model not passing to view

552 views Asked by At

I'm starting out with backbone.js building my first project with backbone-boilerplate.

I have a module named Navitem with a view called Sidebar:

Navitem.Views.Sidebar = Navitem.Views.Layout.extend({
    template: "navitem/sidebar",
    tagName: 'ul',
    beforeRender: function()
    {
      var me = this;
      this.options.navitems.each(function(navitem)
      {
        //insertView from Layout datatype
        me.$el.append(new Navitem.Views.Item({
          model: navitem //select the 'ul' in sidebar view and append an Item with model navitem
        }).render().el);
      });
      return this;
    }
  });

When the sidebar is constructed, a collection containing many Navitem.Model's are passed into it. After debugging, model:navitem seems to be working correctly and passing in the right navitem model to the new Navitem.Views.Item({...}). That class looks like:

Navitem.Views.Item = Navitem.Views.Layout.extend({ 
    tagName: 'li',
    template: 'navitem/default'
    events: {
      click: "navRoute"
    },
    navRoute : function()
    {
      app.router.go(this.model.get('target'));
      return this;
    }
  });

The template looks like <a href="#"><%= model.get('label') %></a>.

For some reason when I call Item.render() in the first code block, it whines that model is undefined in the view. I can't seem to figure out why this is happening. Any thoughts?

2

There are 2 answers

2
Jad On

Might be related to what was answered here : Backbone.js: Template variable in element attribute doesn't work

You need to pass the model as a plain JSON to your template (unless maybe you're using another version?)

Hope this helps!

0
jonahlyn On

I'm doing something similar in a program that I wrote using Backbone Boilerplate and Backbone LayoutManager.

Try adding a serialize function to your Navitem.Views.Item view:

// provide data to the template
serialize: function() {
    return this.model.toJSON();
}

and then in the beforeRender function of Navitem.Views.Sidebar:

beforeRender: function(){
  _.each(this.options.navitems.models, function(model){
    var view = new Navitem.Views.Item({model: model});
    this.insertView(view);
  }, this);
}

and the navitem/default template could look like this:

<%= label %>

This is untested code (using your views and collections) but doing this has been working for me.