我正在使用backbone.js以及
jquery和underscore.js
这是我的一些代码(它还没有做任何事情).奇怪的是,在点击“/#用户”的URL时,没有错误.错误发生的唯一时间是当我点击去另一个哈希,然后点击返回到“/#用户”.这是我的代码的一部分,线路接收到最终的错误Users = new Users();错误说“用户不是构造函数”:
var User = Backbone.Model.extend({ url: function(){return 'api/user/id/' + this.id;} }); var Users = Backbone.Collection.extend({ model: User,url: function(){return 'api/users';},initialize: function() { } }); var UsersView = Backbone.View.extend({ initialize: function() { this.users = this.options.users; this.render(); },render: function() { _(this.users).each(function(){ // $('#app').append('here'); }); var template = _.template($('#usersTemplate').text()); $(this.el).html(template({users: this.users})); $('#app').html(this.el); } }); var UserView = Backbone.View.extend({ initialize: function() { this.user = this.options.user; this.render(); },render: function() { var template = _.template("hello {{user.name}}"); $(this.el).html(template({user: this.user.toJSON()})); $('#app').html(this.el); } }); var Controller = Backbone.Controller.extend({ routes: { 'dashboard' : 'dashboard','users' : 'showusers' },showuser: function(id) { UserList.fetch({ success: function(){ new UserView({user: User}); },error: function(){ alert('an error of sorts'); } }); },showusers: function() { Users = new Users(); Users.fetch({ success: function(Users) { new UsersView({users: Users}); },error: function() { } }); },dashboard: function() { Users = new Users; Users.fetch({ success: function() { new UsersView({users: Users}); },error: function() { } }); } }); $(document).ready(function(){ var ApplicationController = new Controller; Backbone.history.start(); });
如果你好奇,附带的html:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="utf-8"> <title>Administration Panel</title> <!-- Framework --> <script src="/javascripts/jquery.min.js"></script> <script src="/javascripts/underscore.min.js"></script> <script src="/javascripts/backbone.js"></script> <!-- Application --> <script src="/javascripts/application.js"></script> <script id="usersTemplate" type="text/x-underscore-template"> asdf </script> </head> <body> <div> <a href="#dashboard">Dashboard</a> <a href="#users">Users</a> <a href="#products">Products</a> <a href="#orders">Orders</a> <a href="#pages">Pages</a> <a href="#settings">Settings</a> </div> <div id="app"></div> </body> </html>
解决方法
新的只能用一个Function作为操作数.
new {} // Error: ({}) is not a constructor
在上下文中检查用户的类型:当引发异常时,它不是Function.
快乐的编码
alert(typeof(Users))应该做的伎俩.结果应该是“函数”可用作构造函数.记下在失败的情况下是什么,看下面的原因.
一个有问题的场景(用户=新用户)可能是:一个对象是从“功能用户”构建的,然后将对象(现在不是一个功能/构造函数)分配给用户,以便下一个新的用户将去kaboom! (看看这两个showusers和仪表板 – 那个行为真的有意义吗?)
“正确”代码很可能:var users = new Users; users.blahblah(…);也就是说,使用新的局部变量,并且不覆盖全局用户变量/属性.
仅当“返回”为“#foobar”(Fragment Identifier)时才会生成错误的原因是没有新页面实际加载,因此JavaScript未被重新加载,并且正在使用当前(现在已损坏的用户). KABOOM!
If the targeted element is located in the current document,a user agent may simply focus the targeted element without having to reload it …