Backbone.js 为什么主干认为我';我把一个对象当作一个函数?
将主干添加到Rails应用程序中,我在应用程序名称空间中创建了一个post模型,如下所示Backbone.js 为什么主干认为我';我把一个对象当作一个函数?,backbone.js,Backbone.js,将主干添加到Rails应用程序中,我在应用程序名称空间中创建了一个post模型,如下所示 var app = { this.models.post = new app.Models.Post(); postDetails: function (id) { console.log(id); var post = new app.models.post({id: id}); this.post.fetch({ succe
var app = {
this.models.post = new app.Models.Post();
postDetails: function (id) {
console.log(id);
var post = new app.models.post({id: id});
this.post.fetch({
success: function (data) {
$('#content').html(new PostView({model: data}).render().el);
}
});
}
在路由器中,我创建了以下路由
"posts/:id": "postDetails"
当我导航到/posts/4时,我得到一个uncaughttypeerror:object不是一个函数,当我尝试像这样调用模型上的fetch时
var app = {
this.models.post = new app.Models.Post();
postDetails: function (id) {
console.log(id);
var post = new app.models.post({id: id});
this.post.fetch({
success: function (data) {
$('#content').html(new PostView({model: data}).render().el);
}
});
}
根据主干文档,我应该能够调用模型上的fetch来从服务器检索数据。为什么主干认为我将对象视为函数?问题是您已将post
声明为局部变量var post
,但随后尝试将其作为成员访问this.post
。您需要以下任一选项:
this.post = new app.models.post({id: id});
this.post.fetch({ ...
或者这个:
var post = new app.models.post({id: id});
post.fetch({ ...
(区别在于局部变量var post
在瞬态范围内声明,并在postDetails
完成后丢弃;而实例变量this.post
被添加到路由器对象中,并且通常在应用程序的整个生命周期内都有效。)您这样做:
this.models.post = new app.Models.Post();
假设将app.models.post
设置为app.models.post
模型的实例。然后您尝试这样做:
var post = new app.models.post({id: id});
但您只能在函数上使用:
new构造函数[([arguments])]
参数
构造函数
指定对象实例类型的函数
你可能想说:
var post = new app.Models.Post({ id: id });
或者类似的东西。到底是哪一行导致了错误?实际上,是这一行var post=new app.models.post({id:id})代码>。我把它改为var post=new app.Models.post
,它告诉我Uncaught TypeError:Object[Object Object]没有方法“fetch”