r/javascript • • Sep 02 '13

Backbone and RequireJS module definition question

Hello, I've been developing a Backbone app with different modules, and as it's now grown larger I'm looking to organise it with the AMD pattern and RequireJS.

I've been looking at different tutorials and articles about how to go about this. I have a couple of questions though, and was hoping someone here could help me out.

  1. Is there any major difference between these two Module definitions, I personally think the second is neater when it comes to a large amount of definitions?

define(function (require) {
        
           "use strict";
        
            var $           = require('jquery'),
                Backbone    = require('backbone'),
                Module1      = require('Module1'), 
         
                Employee = Backbone.Model.extend({
         
                    urlRoot: "/employees",
         
                    initialize: function () {
                        this.reports = new EmployeeCollection();
                        this.reports.url = this.urlRoot + "/" + this.id + "/reports";
                    }
         
                });

and:

define(['jquery', 'backbone', 'Module1'], function (jQuery, Backbone, Module1) {
        
           "use strict";
        
            var Employee = Backbone.Model.extend({
         
                    urlRoot: "/employees",
         
                    initialize: function () {
                        this.reports = new EmployeeCollection();
                        this.reports.url = this.urlRoot + "/" + this.id + "/reports";
                    }
         
                });

2. In the initialisation of my views, is there any problem using

_.bindAll(this, 'render', 'confirmDelete', 'edit');

over

var self; self = this;

I've already used _.bindAll in almost all my views, so I'd prefer to not have to change that.

Any comments would be greatly appreciated.

5 Upvotes

16 comments sorted by

3

u/enkideridu Sep 02 '13 edited Sep 02 '13

regarding bindAll

I typically put _.bindAll(this) into every view's initialize instead of enumerating every method that needs it. Saves the trouble of having to change 2 places whenever I add/remove/rename a method.

I don't see how you would be able to use var self; self = this; to replace what _.bindAll does. Where are you putting self, and how are you passing it to the other methods?

edit: apparently you only have to write _.bindAll()
e.g.

initialize : function () {
    _.bindAll();
},

2

u/user84738291 Sep 02 '13

In regards to how you would use var self; self = this; I read this code snippet

define(['jquery', 'use!backbone','models/model'], function($, Backbone, Model){

var self,

View = Backbone.View.extend({

    // Represents the actual DOM element that corresponds to your View (There is a one to one relationship between View Objects and DOM elements)
    el: 'body',

    // View constructor
    initialize: function() {

        // Storing the View context
        self = this;

        // Setting the View's model property to the passed in Model
        this.model = new Model({
            message: "You are now using Backbone, Require, and jQuery!"
        });

    },

    events: {
        "click #example": "promptUser"
  },

    render: function() {

        // Updates the text of the element with an ID attribute of example
        self.$el.find("#example").text("This is an example");

    },

    promptUser: function() {
        prompt("Isn't this amazing?", "Yes, yes it is");
    }

});

// Returns the entire view (allows you to reuse your View class in a different module)
return new View();

});

from here: http://gregfranko.com/blog/using-backbone-dot-js-with-require-dot-js/

1

u/enkideridu Sep 02 '13

It hadn't occurred to me that using RequireJS (or any module system) would let you do that until now, thanks for the link!

It's certainly not a Backbone standard practice since it requires each 'var self' to be in its own clojure, which would be much more bothersome to work with if it weren't for each AMD module already being in its own clojure.

Correct me if I'm wrong, but there does seem to be a rather significant limitation - you won't be able to create two instances of the same base View with this method. i.e. You'll always have to return new View() and can't return View. ergo you won't be able to do this:

var BaseView = Backbone.View.extend({/* stuff */}),
viewOne = new BaseView({configurations}),
viewTwo = new BaseView({differentConfigurations});

viewOne and viewTwo would share the same variable self, and viewTwo's constructor would have overwritten viewOne's self to point to "viewTwo".

0

u/[deleted] Sep 02 '13

[deleted]

2

u/enkideridu Sep 02 '13

Binding every function is exactly the point.

Sure it might be slower, but only by around 0.000013 seconds per object. You'll only notice a ~100ms difference when you need to initialize 8000 views at the same time, at which point you have a totally different problem.

Take a look at this [sample View from Addy Osmani's Backbone Fundamentals] (https://github.com/addyosmani/backbone-fundamentals/blob/gh-pages/practicals/todo-jqm-app/app/modules/view/abstract/BasicView.js?source=cc)

Imagine having to keep track of which methods need to be bound and enumerated, and every time you remove or rename a method you have to scroll up to change the parameter of bindAll otherwise you'll get an error and the code won't run, but only if it was an enumerated and bound method. Now imagine doing that for every view your application has. That is too much mental overhead.

1

u/user84738291 Sep 02 '13

Thanks for the info. Think I'll be switching to _.bindAll();

1

u/user84738291 Sep 02 '13

For some reason reddit has numbered my second question as 1 again?!

1

u/jonathanrmumm Sep 02 '13

By default, the first definition pulls in the dependencies at run-time, the second at "compile"-time. The main practical difference here is when you run the RequireJS optimizer, in the first definition, those dependencies will not be included in the optimized module, whereas in the second one it will (unless you specify findNestedDepencies: true in your mainConfigFile).

1

u/user84738291 Sep 02 '13

Thanks for the reply, if I understand correctly in the first bit of code, jQuery Backbone and Module1 will be retrieved from the sever on page load after optimisation has run (unless I set findNestedDepencies) instead of being included in 'bundle.js'

2

u/jonathanrmumm Sep 02 '13

That's correct. I didn't understand your second question but I don't see why you wouldn't be able to continue using bindAll.

1

u/user84738291 Sep 02 '13

Okay, Thanks!

Second question was just asking, any major difference between using underscore's bind function to keep the context of the view, or to store the context in a variable named self.

So in a click handler for the view I would either go

(using _.bindAll )

this.model

or (using var self = this )

self.model

But I think you're correct, I can't see any reason why I wouldn't continue this way. I can't see it making a big difference.

2

u/aeflash Sep 02 '13

In the first example, RequireJS will load your module, detect the synchronous requires, parse them out and replace them with async equivalents, and then eval() the result. A bit trickier to debug because it's doing some source transformation, and when you place a breakpoint, you're in the eval'ed (program) space. A shame, because the syntax is cleaner, adding more deps is easier, and not dependent on the order of arguments in 2 places.

The second will just do the async dependency management as you'd expect, but gets more and more verbose and cumbersome as you add more dependencies.

Honestly, this is why I like the CommonJS/Browserify module style over AMD/r.js. Less boilerplate, and the end result is very similar.

0

u/[deleted] Sep 02 '13

[deleted]

1

u/enkideridu Sep 02 '13

If you use this.model.bind (for those newer to Backbone, Model.bind was renamed to Model.on in Backbone 0.9.0 but was kept as an alias), make sure you remember to call this.model.off (or this.model.unbind) when you're removing the view, otherwise the model will keep a reference to it and it won't get garbage-collected.

It's unfortunate that listenTo doesn't have an optional context parameter. I suppose you could do

this.listenTo(this.model, 'change:prop', _.bind(this.render, this));  

But that seems slightly less elegant than just sticking _.bindAll() into the view's initialize

1

u/user84738291 Sep 02 '13

I am using model.bind, as I started writing this before 0.9. All my views have a close method, ran into the zombie problem a good while ago.

0

u/[deleted] Sep 03 '13

[deleted]

1

u/user84738291 Sep 03 '13

I can see that. Semantically it does make more sense, but there are worse examples of method naming. I wouldn't get hung up on it.

1

u/enkideridu Sep 14 '13 edited Sep 15 '13

I actually quite like "on" and thought it was exemplary of concise and intuitive method naming.

"On my cue, hit him on the head" maps quite nicely to on(cue, smash.bind(him.head))

"Off" on the other hand did take some getting used to