简体   繁体   English

使用节点上的主干配置$ .ajax以进行誓言测试

[英]Configuring $.ajax with backbone on node for testing with vows

(Edited to greatly simplify) (编辑以大大简化)

On node I have the following server.js file. 在节点上,我有以下server.js文件。

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) “无法调用未定义的方法'ajax'”(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. 好了,这里有许多中间步骤,但是在加载文件时,期望“ this”在浏览器中是“窗口”,在服务器上是“ global”。 executed on node "this" = {}. 在节点“ this” = {}上执行。

So the question, "How do I set 'this' to global" inside the backbone.js file? 因此,orbone.js文件中的问题“如何将'this'设置为global”?

On Backbone >= 1.x, you can simply assign Backbone.$ rather than using Backbone.setDomLibrary . 在Backbone> = 1.x上,您可以简单地分配Backbone.$而不是使用Backbone.setDomLibrary

Solution for Backbone < 0.9.9 骨干解决方案<0.9.9

The first issue you need to address is how you are running this on Node anyway. 您需要解决的第一个问题是如何在Node上运行它。 Nodejs is a server-side JS environment, but it does not include any logic for controlling a DOM. Node.js是服务器端JS环境,但不包含任何用于控制DOM的逻辑。 For that you need to load something like JSDom. 为此,您需要加载类似JSm的内容。

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. 设置了DOM环境后,您可以将jQuery及其代码加载到其中,并且它应该像浏览器一样工作。

To answer your question specifically though, loading jQuery into the global is a bit of an ugly way to do it. 但是,要专门回答您的问题,将jQuery加载到global是一种难看的方法。 You should use Backbone's setDomLibrary function to set $ to what you want. 您应该使用Backbone的setDomLibrary函数将$设置为所需的值。

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. 但是,如果尝试执行任何DOM功能,这将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM