我想从 View 中传递和获取一个值,以对集合的模型使用进行建模,当我使用集合时,我能够将值传递到模型中,但它不起作用。我不知道这里的问题在哪里是我的代码。
我的模型
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
});
我在这里进入控制台----> [],collection fetch value[object Object],问题在哪里以及如何保存和获取值。
最佳答案
试试这个:
var self = this;
collection.fetch()({
success: function (data) {
console.log("collection fetch value "+data);
self.render();
}
});
您只想在获取成功后才执行渲染。 fetch 方法异步运行。这意味着在 fetch 方法仍在做它的事情时,它之后的所有内容仍将尝试执行。通过将 render 方法放在成功回调中,您可以确保在您实际拥有该数据之前不会尝试使用您的集合数据。
关于javascript - 如何将值从集合传递到 backbone.js 中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22840215/