Javascript 主干视图上没有“应用”方法
我一直试图在我(相当简单)的主干/咖啡脚本代码中找到一个奇怪的bug 运行应用程序时,我遇到以下错误:Javascript 主干视图上没有“应用”方法,javascript,backbone.js,coffeescript,Javascript,Backbone.js,Coffeescript,我一直试图在我(相当简单)的主干/咖啡脚本代码中找到一个奇怪的bug 运行应用程序时,我遇到以下错误: Uncaught TypeError: Object #<IndexView> has no method 'apply' 以及以下观点: class App.IndexView extends Backbone.View template: "index" el: $("#container") initialize: -> @
Uncaught TypeError: Object #<IndexView> has no method 'apply'
以及以下观点:
class App.IndexView extends Backbone.View
template: "index"
el: $("#container")
initialize: ->
@render()
render: ->
get_template(@el, @template, @domEvents)
domEvents: ->
$("#searchInput").on "change keydown", ->
if $(this).val().length >= 0
$("#placeholder").css("display", "none")
else
$("#placeholder").css("display", "inline-block")
从我的测试中,似乎只要我去掉代码的Backbone.history.start({pushState:true})
行,这个错误就会消失。不幸的是,我的应用程序需要pushState,所以不可以删除它
有人知道这里可能出了什么问题吗?当您在路由器中定义
索引时,您缺少了一个->
:
class window.App.Router extends Backbone.Router
#...
index:
@view = new App.IndexView()
结果是在构建App.Router
类时执行new App.IndexView()
,并且index
成为new App.IndexView()
的值;此外,在此上下文中,@
是类本身,因此您最终设置App.Router.view=new App.IndexView()
。JavaScript如下所示:
Router.prototype.index = Router.view = new IndexView();
然后,因为你的路线:
routes: {
"": "index",
#...
}
路由系统尝试调用router.index
作为一个函数(用于确保适当的调用上下文),以响应路由请求;但是router.index
是一个视图实例,而不是一个函数/方法,因此您会得到错误:
uncaughttypeerror:对象#没有方法“apply”
因为不能对视图实例调用apply
大概,您的Backbone.history.start({pushState:true})
会触发到索引的初始路由
因此,请修复类定义,将索引
定义为一个方法,然后重试
另一方面,在路由器的初始化中调用主干.history.start({pushState:true})
有点奇怪。委员会:
创建所有路由器并正确设置所有路由后,调用Backbone.history.start()
开始监视hashchange
事件和调度路由
因此,可能在所有路由正确设置并准备就绪之前启动历史记录系统。这可能会导致一些奇怪的事情发生。哇。。。就这样。。。唉,我也把Backbone.history.start()移到了新路由器()后面的一行。非常感谢!
routes: {
"": "index",
#...
}