Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wire a Backbone View to a meteor handlebars template?

Looks like Backbone.view, meteor and handlebars have overlap functionality when it comes to manipulating a section of the DOM. I looked at the ToDo app which is suppose to use Backbone, but in reality, they only use the Router.

Backbone views also deal with templates... but they sound so different from meteor templates. Besides, it looks like both backbone & meteor can update the ui on a model update.

ok, I am lost!? Who does what?

Is Backbone really useful for a Meteor App? Can Backbone & Handle bars coexist? and if they can, in the Meteor context, how to wire a Backbone view to a handlebars template?

EDIT: found the todo-backbone example. it seems to confirm that you can go either:

  • meteor + backbone + underscore templates
  • or... meteor + handlebars

meteor+backbone+handlebars doesn't seem like a viable option...

Thank you

like image 927
Olivier Refalo Avatar asked May 17 '12 02:05

Olivier Refalo


1 Answers

It's very easy and no more work than using the Underscore template. Here's an example .html file:

<template name="user_list">
<ul>
  {{#each users}}
  <li>{{name}}</li>
  {{/each}}
</ul>
</template>

And here's an example .js file:

Users = new Meteor.collection("users");

if (Meteor.is_client) {
  Template.user_list.users = function() {
    return Users.find();
  }

  window.UserView = Backbone.View.extend({
    initialize: function() {
      _.bindAll(this, 'render');
    },
    template: function() {
      Meteor.ui.render(function() {
        return Template.user_list();
      });
    },
    render: function() {
      $(el).empty().append(this.template());
    }
  });
}

You can then use a Router or another View to manage when you want to display the UserView just like you would in any other Backbone.js app.

The key is to use the Meteor.ui.render or other Meteor.ui method to render the HTML so that it's reactive.

like image 105
Aaron Avatar answered Jan 01 '23 08:01

Aaron