Undefined id fetch
Undefined id fetch
我的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() ) );
});
希望有帮助!编码快乐!
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- fetch() 函数未在 Ubuntu Chromium 浏览器上定义
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 当json解析空响应时,Whatwg-Fetch失败,我该如何防止它
- 通过id和class属性获取元素
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 使用当前日期生成随机id
- Javascript-ID冲突的几率
- Href:当前DIV中的目标ID
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- Javascript复选框函数:;缺少:在属性id之后"
- Twitter引导程序Typeahead-Id&标签
- 如何与特定ID交谈
- Undefined id fetch
- Linkedin JSAPI to fetch group id's