5
我想传递并从视图中获取值以模拟集合的使用,我能够在将值传递给模型时将其传递给模型工作。我不知道问题在哪里,是我的代码。如何将值从集合传递给backbone.js中的模型
我的模型
var PostwallModel=Backbone.Model.extend({
urlRoot: 'http://localhost:3400/post',
idAttribute: '_id',
defaults : {
userId: '',
userName: " ",
postmsg : "unknown"
},
initialize: function() {
console.log("<><><>post model initialize<><><><><>");
},
// Delete item (row) from
clear: function() {
this.destroy();
}
});
我的收藏
var PostwallCollection = Backbone.Collection.extend({
url: 'http://localhost:3400/post',
model: PostwallModel
});
**here is my view**
var PostwallView = Backbone.View.extend({
el: $("#page"),
template: _.template(PostwallTemplate),
events: {
'click #postinwall' : 'submitpost',
},
initialize: function() {
console.log("_______postmodel");
this.model = new PostwallModel();
var obj= new PostwallModel();
obj.set({userId:'123',userName:"str ji",postmsg:'the post is here'});
console.log(obj.get('postmsg'));
obj.toJSON();
console.log(JSON.stringify(obj));
// console.log(obj.get('userName'));
var collection = new PostwallCollection();
_.bindAll(this, 'submitpost');
console.log(collection);
collection.add(obj,{id:1});
console.log("collection"+collection);
console.log("collection fetch value "+JSON.stringify(collection.fetch()));
this.render();
},
render: function() {
alert(" render function");
},
submitpost: function(e) {
//Save post model to server data
e.preventDefault();
var post_data = JSON.stringify(this.getFormData(this.$el.find('form')));
//
//this.model.save(post_data);
this.model.set(post_data);
this.collection.add(this.model);
return false
},
//Auxiliar function
//how to get data from textarea
});
我在这里越来越控制台----> [],收藏价值取[目标对象],问题在哪里以及如何保存和获取值。
你知道吗,那.fetch()是异步操作? console.log(“collection fetch value”+ JSON.stringify(collection.fetch()));将无法工作。你能给jsbin例子更多的帮助吗? –
我没有得到你的观点,请你能提供一些更多的信息@VasilVanchuk – Sport
这就是我说的话:collection.fetch()不返回集合数据,导致获取使http请求和数据只能访问成功的处理响应。所以,当你写如console.log(“集合提取值”+ JSON.stringify(collection.fetch()));你不会看到收集数据 –