Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 如何将urlRoot传递给主干中的模型_Backbone.js - Fatal编程技术网

Backbone.js 如何将urlRoot传递给主干中的模型

Backbone.js 如何将urlRoot传递给主干中的模型,backbone.js,Backbone.js,我需要在运行时将urlRoot传递给模型,因为模型的几个不同类使用不同的urlRoots 这是我的模型: App.Models.Table = Backbone.Model.extend({ }); 下面是我将使用它的地方: var m = new App.Models.Table(); var t = new App.Collections.Tables(m, { url: this.url }); var tables = new App.Views.Tables({ collection

我需要在运行时将
urlRoot
传递给模型,因为模型的几个不同类使用不同的
urlRoot
s

这是我的模型:

App.Models.Table = Backbone.Model.extend({ });
下面是我将使用它的地方:

var m = new App.Models.Table();
var t = new App.Collections.Tables(m, { url: this.url });
var tables = new App.Views.Tables({ collection: t, template: this.template });
this.url
根据调用它的事件返回正确的值。我把我的模型传错了吗?这是我的收藏:

App.Collections.Tables = Backbone.Collection.extend({
    url: this.url,
    model: App.Models.Table,
    initialize: function(models, options) {
        if (options && options.url) {
            this.url = options.url;
        }
        this.fetch({
              success: function(data, options) {

            }
        });
    }
});

如何将
this.url
传递给我的模型?

url应该是字符串常量或返回字符串的函数。在您的收藏中,您可能希望执行以下操作:

App.Collections.Tables = Backbone.Collection.extend({
    url: function() { return "http://my.url/" },
    // or, url: "http://my.url"
});
使用匿名函数可以在发送请求之前处理某些数据(即,可能修改字符串)


我是否正确理解了您的问题?

假设
此.url在您的示例中是正确的url,然后执行以下操作:

table = new App.Models.Table({
    id: id
});
table.urlRoot = this.url;

在运行时,当我运行click事件时,我得到一个错误,即必须定义URL。这是什么?我是说这指的是什么?我只是想把urlRoot传递到我的模型中。我不确定你在问什么。如果我为
urlRoot
输入一个正确路径的字符串,我的应用程序就会正常工作。但是我需要能够在运行时根据定义urLRoot的route.where更改
urLRoot
。如果它在表外,您需要使用self技巧,var self=this,然后传递urlRoot:self.urlRootWell,我需要能够传递一个字符串作为我的urlRootI仍然得到一个“url”属性或函数必须指定
,即使我为
m.urlRoot
硬编码了一个字符串,您可能会看到一些事实错误:
urlRoot:this.urlRoot
a=a
不同,因为
this
的值是调用extend时的上下文,最有可能是窗口。当然,这仍然是错误的。另外,他将
url
传递给集合的方式也很好,因为这是在构造函数中分配给实例的第二个参数(选项)。@fencliff,我如何完成上面的工作?@sehummel,我想阅读javascript中的
this
上下文变量会让您受益匪浅,以便您真正理解它。我还建议大家花点时间仔细阅读主干文档,或者尝试一些教程。好的,当然可以。谢谢,芬克利夫