9

這些是我在BackBone.js上工作的第一天。我實際上堅持與路由器部分,因爲我在控制檯中出現錯誤「錯誤:必須指定url屬性或函數」。這是我的場景;我有一個點擊功能,它動態地形成一個REST URL,並相應地從服務器獲取數據。錯誤:必須指定url屬性或函數

這裏是點擊功能代碼

function onUserClick(obj){ 
    var userID=$(obj).attr('id'); 
    window.location.href="#"+userID+"/"; 
    var userRouter = new UserRouter; 
} 

而且我在路由器下面的代碼

var userModel; 
var UserRouter = Backbone.Router.extend({ 
    routes:{ 
     ":userid/":"getUsers" 
    }, 
    getUsers:function(userid){ 
     var url="http://myserver.com/users/"+userid; 
     userModel = new UserModel({urlRoot:url}); 
     var userView = new UserView({el:$(#"container")}); 
    } 
}); 
var UserModel = Backbobe.Model.extend({}); 
var UserView = Backbone.View.extend({ 
    model:userModel, 
    initialize:function(){ 
     _.templateSettings = { 
      interpolate: /\{\{\=(.+?)\}\}/g, 
      evaluate: /\{\{(.+?)\}\}/g 
     }; 
     this.model.fetch(); 
     this.model.bind("change",this.render,this); 
    }, 
    render:function(){ 
     var data=this.model.toJSON(); 
     var userTemplate=_.template($("#userTemplate").text()); 
     var htmlData=userTemplate({ 
      "userData":data 
     }); 
     $(this.el).html(htmlData); 
    } 
}); 

有人可以幫助我在這裏找出問題?我知道我在這裏做錯了什麼,並尋求專家建議。這個場景的一個令人興奮的例子非常感謝。

+0

你可以給你的錯誤一些背景嗎?你有什麼努力去解決這個問題呢? – tkone 2012-04-09 18:01:27

回答

21

你打電話你的模型fetch

var UserView = Backbone.View.extend({ 
    model: userModel, 
    initialize: function() { 
     // ... 
     this.model.fetch(); 

但是你沒有給你的模型url屬性:

var UserModel = Backbone.Model.extend({}); 

fetch方法會談到服務器,它使用url要做到這一點:

urlmodel.url()

Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]" , falling back to "/[urlRoot]/id" if the model is not part of a collection.

default implementation for a Model's url看起來是這樣的:

url: function() { 
    var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); 
    if (this.isNew()) return base; 
    return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); 
}, 

你沒有urlRoot,你沒有一個集合委託的URL代,並且您還沒有覆蓋url所以urlError()被調用而這也正是你的錯誤信息來自於。

您的UserModel需要RESTful url屬性或功能,以便您可以從服務器獲取fetch實例。或者,您可以使用客戶端環境中已有的數據創建模型(只要您不打算通過Backbone保存任何內容)。

+0

感謝您的回答,這很有幫助。 – 2012-04-21 19:22:15

相關問題