snewcomer
snewcomer

Reputation: 2135

Using listenTo in Backbone and RequireJS

So before using RequireJS, I had the following code below that worked fine and pulled in the Posts from from the server rather than a .fetch() call...Given the modular pattern of RequireJS and the fact that I can't have this nice app.posts variable floating around for other files, is there a way to still use the $(document).ready function and have the posts variable still respond to the 'reset' event? Currently, I am only getting this to work with .fetch (see below).

routes.js

router.get('/fund', function(req, res) {
  Post.find({}, function(err, docs) {
    res.render('fund', {
      posts: docs //passed to bootstrapPosts in script element
    });
  });
});

index.jade

var bootstrapPosts = !{JSON.stringify(posts)};

collections.js

app.posts = new app.PostCollection(); //app. == namespacing

app.js

$(document).on('ready', function() {
  app.post_appView = new app.postAppView(); 
  app.posts.reset(bootstrapPosts);
  app.posts.fetch(); //**Don't want to use this**//
});

post_appView.js

initialize: function() {
    this.listenTo(app.posts, 'reset', this.addAll);
}

=====

With RequireJS

AppView.js

define([
  'jquery',
  'underscore',
  'backbone',
  'models/models',
  'views/postView',
  'collections/collections',
  'globals'], function($, _, Backbone, PostModel, PostView, posts, globals){

   return AppView = Backbone.View.extend({
      el: '#securities',
      initialize: function() {
        this.listenTo(posts, 'add', this.addOne);
        this.listenTo(posts, 'reset', this.addAll);
        posts.fetch({reset: true}); // I DON"T WANT TO USE THIS.
      },

Upvotes: 1

Views: 109

Answers (1)

snewcomer
snewcomer

Reputation: 2135

Well I have answered my own question. Did not know I could actually include a require statement in my actual view. This allows me to do away with the fetch call and just pass in all the variables in expressJS index.jade

index.jade

script(type="text/javascript").
      require(['lib/domReady', 'collections/collections', 'globals'], function (domReady, posts, globals) {
        domReady(function() {
          posts.reset(globals.bootstrapPosts);
        });
      });

appView.js

define([
  'jquery',
  'underscore',
  'backbone',
  'models/models',
  'views/postView',
  'collections/collections',
  'globals'], function($, _, Backbone, PostModel, PostView, posts, globals){

   return AppView = Backbone.View.extend({
      el: '#securities',
      initialize: function() {
        this.listenTo(posts, 'add', this.addOne);
        this.listenTo(posts, 'reset', this.addAll);
      },

Upvotes: 1

Related Questions