我正在使用骨干构建应用程序,而且我无法有效地进行collection.fetch。有两个具体问题:
我需要使用fetch查询传递一些值,以便接收查询的控制器可以根据这些值构造SQL查询。
我希望能够从持久数据库中获取适当的值并将它们返回到集合中,以使集合保持最新。
这是我的代码:
//模型
class QuestionModel extends Backbone.Model{
defaults(){
return{
type:true,
question:" "
};
}
idAttribute = "question";
url = "question";
}
//收集
class SurveyCollection extends Backbone.Collection {
constructor(options) {
super(options);
var self = this;
this.on("add", function (model) {
var self = model;
model.save({}, {
success: function () {
Log.success("Saved " + self.get("question"));
app.views.indexView.render();
},
error: function () {
Log.failure("Saved " + self.get("question"));
}
});
}, this);
this.fetch();
}
model = QuestionModel;
url = "survey";
}
//在视图中获取请求
this.collection.fetch({
data:{
values: 100,
type: "normal"
},
success: function(collection, response) {
_.each(collection.models, function(model) {
Log.show(model.get("question"));
})
},
error: function(err){
Log.error("couldn't receive data");
}
});
控制器:
index(req, res) {
log.Log.show("Received index request : values = " + req.body.values + " type : " + req.body.type);
sqlConnector.query('select * from question', function (err, rows, fields) {
if (!err) {
_.each(rows, function (row){
log.Log.show("row : " + row);
})
res.send(rows);
} else {
log.Log.show("error : " + err);
res.status(500).send(err);
}
});
}
目前,MySQL数据库包含4个问题值:
John
Jacob
当我加载页面时(即调用render()和fetch()时),
the browser console shows 2 values:
Jacob
Jacob
the server console shows
Received index request : values = undefined type : undefined
show rows; [object Object]
show rows; [object Object]
当我添加另一个值' Jasmine'然后再次调用fetch:
the browser console shows 2 values:
Jasmine
Jasmine
Jasmine
the server console shows
Received index request : values = undefined type : undefined
show rows; [object Object]
show rows; [object Object]
show rows; [object Object]
如果我添加其他价值' Jeremy'然后再次调用fetch:
the browser console shows 2 values:
Jeremy
Jeremy
Jeremy
Jeremy
the server console shows
Received index request : values = undefined type : undefined
show rows; [object Object]
show rows; [object Object]
show rows; [object Object]
我需要解决此问题,并确保在两端提取正确的值