我想看看当在扩展模型上指定了urlRoot
时,如何使用model.save()
方法将模型保存到服务器,但是当我请求model.fetch()
或do model.save()
时,ajax请求从不触发。注意:我想这在不使用Collection的情况下是可能的吗?
HTML
<div id="placeholder"></div>
<script type="text/template" id="view_template">
Hello <%= name %>, here is your script <%= script %>
</script>
模型
window["model"] = Backbone.Model.extend({
initialize: function () {
console.log("CREATED");
},
defaults:{
name:"Please enter your name",
script:"Hello World"
},
urlRoot: "index.aspx",
validate: function (attrs) {
},
sync: function (method, model, success, error) {
console.log("SYNCING", arguments);
}
});
视图
window["view"] = Backbone.View.extend({
template:_.template($("#view_template").html()),
initialize: function () {
console.log("INITIALISED VIEW");
this.model.bind("change","render",this);
},
render: function (model) {
console.log("RENDERING");
$(this.el).append(this.template(model));
return this;
}
});
应用程序
$("document").ready(function () {
var myModel = new model({
name: "Stack Overflow",
script: "alert('Hi SO')"
});
var myView = new view({
model: myModel,
el: $("#placeholder")
});
console.log("SAVING");
myModel.save();
console.log("FETCHING");
myModel.fetch();
});
正如您在应用程序中看到的那样,我调用了save & fetch
,但根据文档,这应该会触发带有POST -> SAVE
& GET -> FETCH
的ajax请求。但它所做的就是在sync函数中将参数记录到控制台中。
发布于 2011-10-06 16:32:07
我认为您没有看到任何Ajax请求的唯一原因是您已经覆盖了Model.sync方法。通常,只有当您想要替换在Backbone.sync中实现的默认Ajax同步时,才会这样做。在backbone.js中查看Model.fetch中的以下行:
return (this.sync || Backbone.sync).call(this, 'read', this, options);
我用你的代码做了一个快速测试,如果我重命名你的Model.sync方法,我会看到Ajax请求。
https://stackoverflow.com/questions/7670568
复制相似问题