Error: A “url” property or function must be specified, except url is specified

二次信任 提交于 2019-12-04 17:20:26

defsq answer is good. The only thing missing is to define the idAttribute on your model, since it's not the convention-based id field, but uid.

MessageManager.models.Conversation = Backbone.Model.extend({
    idAttribute: 'uid',
    defaults: {
        uid: '',
        title: '',
        messages: [],
        users: [],
        dateUpdated: null,
        isNew: true,
        message: ''
    },
    urlRoot: "/api/conversations"
});

You don't need to append the "id" manually. Just tell Backbone that your id attribute is uid and everything else will work. In fact, you can event call mymodel.id to get the id of the model -event if it's stored internally as uid. :)

http://backbonejs.org/#Model-idAttribute

Personally I don't like all that default values. Everything will be undefined if you don't set default values, which you can simply guard against with an if (undefined is a falsey value).

if(!model.get("messages")){
   //no messages
}

It happens because you have to specify urlRoot property of the model. Without it url is not considered. So try this maybe:

MessageManager.models.Conversation = Backbone.Model.extend({
    defaults: {
        uid: '',
        title: '',
        messages: [],
        users: [],
        dateUpdated: null,
        isNew: true,
        message: ''
    },
    urlRoot: function() {
        var url = '/api/conversations';
        if (this.get('uid').length > 0) url += '/'+this.get('uid');
        return url;
    }
});

Documentation says:

urlRootmodel.urlRoot or model.urlRoot() Specify a urlRoot if you're using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "[urlRoot]/id" Normally, you won't need to define this. Note that urlRoot may also be a function.

And source code for Backbone.Model url method:

url: function() {
  var base =
    _.result(this, 'urlRoot') ||
    _.result(this.collection, 'url') ||
    urlError();
  if (this.isNew()) return base;
  return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!