Pregunta

(Edited to greatly simplify)

On node I have the following server.js file.

var Backbone = require('backbone');

var Tweet = Backbone.Model.extend({});
var Tweets = Backbone.Collection.extend({
    model : Tweet,
    url: function () {
        return 'http://search.twitter.com/search.json?q=backbone'
}
});

var myTweets = new Tweets();
myTweets.fetch();

When I run this, I get an error that says. "Cannot call method 'ajax' of undefined" (1359:14)

basically that is the result of $ being undefined. Why is it undefined? Well there are a number of intermediate steps but when the file is loaded, it is expecting "this" to be "window" in browser or "global" on server. executed on node "this" = {}.

So the question, "How do I set 'this' to global" inside the backbone.js file?

¿Fue útil?

Solución

On Backbone >= 1.x, you can simply assign Backbone.$ rather than using Backbone.setDomLibrary.

Solution for Backbone < 0.9.9

The first issue you need to address is how you are running this on Node anyway. Nodejs is a server-side JS environment, but it does not include any logic for controlling a DOM. For that you need to load something like JSDom.

When you have some DOM environment set up, you can load jQuery and your code into it and it should work just like a browser.

To answer your question specifically though, loading jQuery into the global is a bit of an ugly way to do it. You should use Backbone's setDomLibrary function to set $ to what you want.

Try something like this:

if (typeof exports !== 'undefined') {
    MyModels = exports;
    Backbone.setDomLibrary(require('jquery'));
    server = true;
} else {
    MyModels = this.MyModels = {};
}

This will fail if you try to do any DOM functions though.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top