gpt4 book ai didi

javascript - 返回主干函数外的变量

转载 作者:行者123 更新时间:2023-11-30 12:55:33 25 4
gpt4 key购买 nike

我正在尝试将 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;
}
});

最佳答案

你误会了。预创建模型并将其传递给 View 。不要试图从 View 渲染代码中提取一些东西,它不应该以这种方式使用。

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()); // :)

关于javascript - 返回主干函数外的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19298477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com