Undefined id fetch

Undefined id fetch

本文关键字:fetch id Undefined      更新时间:2023-09-26

我的backbonejs应用程序有一个模型看起来像:

var Store = Backbone.Model.extend({
   urlRoot: "/stores/" + this.id
});

和我有一个路由器看起来像:

var StoreRouter = Backbone.Router.extend({
   routes: {
      'stores/edit/:id': 'edit'
   },
   edit: function(id){
      var editStoresView = new EditStoresView({
         el: ".wrapper",
         model: new Store({ id: id })
      });
   }
});
var storeRouter = new StoreRouter();
Backbone.history.start({ pushState: true, hashChange: false });

但是在我看来我有:

var EditStoresView = Backbone.View.extend({
   ...
   render: function() {
       this.model.fetch();
       this.$el.append ( JST['tmpl/' + "edit"]( this.model.toJSON() ) );
   }

不幸的是,这给了一个调用localhost/stores/undefined,但我不知道为什么?

你得到"localhost/stores/undefined"调用的原因是因为你有以下代码:

urlRoot: "/stores/" + this.id

当你使用model.fetch()时,它使用urlRoot加上模型的ID来获取数据。换句话说,您应该将urlRoot设置为"/stores/"之类的内容,而不应该直接应用任何ID。

还有一件事,你应该在fetch()方法的" success "回调中编写下面的代码,因为模型数据不会在你调用fetch()时立即可用(因为它是对服务器的同步请求)。

this.model.fetch();    
this.$el.append ( JST['tmpl/' + "edit"]( this.model.toJSON() ) );

改为

   var el = this.$el;
   this.model.fetch({ success : function(model, response, options) {
       el.append ( JST['tmpl/' + "edit"]( model.toJSON() ) );
   });

希望有帮助!编码快乐!