Search code examples
jquerybackbone.jsbrowserify

Why I have to Backbone.$ = require('jquery') in browserify


I am reading this article and practice it myself.

If I remove Backbone.$ = $, the code will not work. Why?

var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;

module.exports = Backbone.View.extend({
  initialize: function(){
    console.log('wuuut')
    this.render();
  },

  render: function(){
    $('body').prepend('<p>wooooooooooooooo</p>');
  }
});

Why in the node js I have to assign jquery to a member in Backbone object?


Solution

  • By default, Backbone has this code:

    // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
    // the `$` variable.
    Backbone.$ = $;
    

    If you load your modules via require, $ isn't available to backbone, so you have to set it manually. And if you don't, Backbone.View, which depends on jQuery won't work.