Property '$' of object #<Object> is

2019-07-03 12:06发布

问题:

i am trying to output some dafault values of a backbone Model via creating a View but the node is showing the error "Property '$' of object # is not a function at _.extend._ensureElement". I can show default values from model directly as i am doing in the code below but not by using view. To show an example i've commented out the //myView = new firstView(); so you can see the output but soon i remove the comments i get the error. Please let me know what is missing and something i am doing wrong. Already tried wrapping the code within $(function(){}) but no luck.

     express = require('express');
     $ = require('jQuery');
     _ = require('underscore');
     Backbone = require('Backbone');
     app = express();

     app.use(express.static(__dirname + ''));
     app.use(express.bodyParser());
     app.listen(process.env.PORT || 3000);

     Person = Backbone.Model.extend({
        defaults: {
            'name': 'Joe Blog',
            'job': 'Web Developer'
        }
     });

     firstPerson = new Person();
     firstView = Backbone.View.extend({

        initialize: function() {
            this.render();
        },
        render: function() {
            console.log(firstPerson.get('job'));
            return this;

        }
     })

     //myView = new firstView();
     console.log(firstPerson.get('name'));

回答1:

Backbone proxies the jQuery library. It usually does so by searching for a global $ variable. Since you execute code in the node environment, you will want to do that manually:

var Backbone = require('backbone'),
    $ = require('jQuery');

Backbone.$ = $;

As a side note, you really should use the var keyword in front of variables in order to make variables local to the function scope. ( See this question )