我试图将profile.toJSON()返回给一个对象,以便在上面的代码之外使用它。我不知道骨干函数究竟是如何工作的,所以我声明了一个全局变量obj并试图用obj = profile.toJSON()来解析数据。当我使用console.log(obj)时,它成功显示我的数据。当我把控制台放在上面的代码之外时,它返回underfined。
var obj;
var ProfileView = Backbone.View.extend(
{
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName)
{
_.each(this.model.models, function(profile)
{
var profileTemplate = this.template(profile.toJSON());
obj = profile.toJSON();
$(this.el).html(profileTemplate);
}, this);
return this;
}
});
答案 0 :(得分:3)
你是错误的结局。预创建模型并将其传递给视图。不要试图从视图渲染代码中提取某些内容,但这并不意味着以这种方式使用。
var Profile = Backbone.Model.extend({});
var ProfileCollection = Backbone.Collection.extend({
model: Profile
});
var ProfileListView = Backbone.View.extend({
...
// Everything render does is rendering
render: function() {
this.collection.each(function(model) {
this.$el.append(
this.template(model.toJSON);
);
}, this);
}
...
});
// Your profile instance is defined outside the view, making
// it de facto available to outside code
var profile = new Profile({
name: 'Fere Res',
rep: 48
});
// The profile we just created gets added to a collection
var profiles = new ProfileCollection([profile]);
// We create the profile list view and pass it the collection
var view = new ProfileListView({collection: profiles});
// When we render the view, the render() code defined above is called.
// You can easily see that all the params/variables it uses are in place
view.render();
// Rendering is done, let's check our model is still available
console.log(profile.toJSON()); // :)
答案 1 :(得分:0)
我有这个代码实际上从json文件中获取数据:
$(function() {
var Profile = Backbone.Model.extend({
defaults: {
tstamp: "",
map:"",
tagsCloud:"",
sentiment: "",
usersCloud: "",
timeline: "",
highlights: "",
signals: ""
},
initialize: function() {
}
});
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'data.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
//obj = profile.toJSON();
//console.log(obj.tstamp);
$(this.el).html(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
setInterval(function() {
profiles.fetch({reset: true});
}, 400); // Time in milliseconds
profiles.bind('reset', function () {
profilesView.render();
});
});
我尝试将配置文件添加到新集合中:
var profiles1 = new ProfileList([profiles]);
var view = new ProfileView({collection: profiles1});
view.render();
console.log(profile.toJSON());
我收到了控制台消息:无法读取未定义的属性“模型”