gpt4 book ai didi

javascript - Backbone.js 我应该在何时何地获取我的集合数据?

转载 作者:行者123 更新时间:2023-11-28 01:30:18 24 4
gpt4 key购买 nike

我对何时何地实例化集合并在主干应用程序中获取它们有点困惑。

我现在已经看到了它的几种实现方式,并且在我非常简单的小型 CRUD 联系人管理应用程序中工作,我正在摆弄它,但我确信有一些我不知道的约定和“陷阱”意识到。

这些是我看过的选项,要么开始工作,要么有点“工作”:)选项 4 似乎是概念上最好的,但我正在搞砸它。

坏主意:1)在我真正使用路由器做任何事情之前,我实例化了一个新集合并调用 fetch,然后在文档就绪语句中启动 app.view。

    // Create an Instance of the collection
App.contacts = new App.Collections.Contacts;

App.contacts.fetch({update: true, remove: false}).then(function() {
new App.Views.App({ collection : App.contacts });
});
  • 这确实有效 - 但如果我要在一个应用程序中拥有多个集合,这似乎并不是真正正确的方法,我认为这个想法失败了。

坏主意:2)当我开始使用路由器时,我想在路由器初始化方法中执行与上面相同的操作,这也有效,但我认为给我留下了同样的问题。

坏主意:3)我尝试在集合 init 方法中获取数据,尽管我在很多地方读到这是一个坏主意,但它似乎有效。

好主意(?):但我不能让它工作:4)我想,当我实例化集合的 View 时,获取集合的数据是有意义的,这样如果我有一个联系人集合和一个任务集合,只有当我在路由器中实例化其 View 时,它们才会从服务器中提取。这对我来说似乎是获胜公式,但是当我尝试将其放入 View init 或 render 方法中时,我的 this.collection.on('add', this.addOne, this); 给了我无法在未定义时调用 .on。 (注意:我尝试将其放入成功函数中)

这让我很头疼,请帮忙。

干杯。

编辑:附加代码,以便我们可以诊断下面讨论的双重负载。

在我的路由器文件中,我正在使用此实用程序 obj :

var ViewManager = {
currentView : null,
showView : function(view) {
if (this.currentView !== null && this.currentView.cid != view.cid) {
this.currentView.remove();
}
this.currentView = view;
return view;
}
}

在我的路由器中:我在我的路线上调用此方法

list: function() {
console.log('backbone loading list route');

var AllContactsView = new App.Views.Contacts({ //init method runs now
collection : App.contacts
});

ViewManager.showView(AllContactsView);

},

我的收藏

App.Collections.Contacts = Backbone.Collection.extend({
model: App.Models.Contact,
url: 'contacts',
});

在我看来

App.Views.Contacts = Backbone.View.extend({
tagName: 'tbody',

initialize: function() {

this.listenTo(this.collection, 'sync', this.render);
this.listenTo(this.collection, 'add', this.addOne);

this.collection.fetch({
// update: true,
// remove: false
});

},

render: function() {
// append the list view to the DOM
$('#allcontacts').append(this.el);

// render each of the single views
this.collection.each( this.addOne, this);
return this;
},

addOne: function(contact) {
var contactView = new App.Views.Contact({ model: contact});
this.$el.append(contactView.render().el);
}

});

在我的 app.js 中

// Run App
jQuery(document).ready(function($) {

// Create an Instance of the collection
App.contacts = new App.Collections.Contacts;

// Init BB Router
new App.Router.Route;
Backbone.history.start(); // Kick it all off.

});

最佳答案

你的观点应该是这样的:

App.Views.Contacts = Backbone.View.extend({
tagName: 'tbody',

initialize: function() {

this.listenTo(this.collection, 'reset', this.render);
this.listenTo(this.collection, 'add', this.addOne);

vent.on('contactR:closeAll', this.closeView, this);

this.collection.fetch();
},
});

关于javascript - Backbone.js 我应该在何时何地获取我的集合数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209676/

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