gpt4 book ai didi

javascript - 为什么我通过点击获得用户的所有模型而不是一键模型?

转载 作者:行者123 更新时间:2023-12-02 14:23:38 24 4
gpt4 key购买 nike

单击集合中的一个模型后,我将获取该用户控制台中的所有模型,而不是单击的模型。谁能帮我吗?

App.js

在 App.js 中将模型发送到另一个 View ,为每个模型创建一个独特的 View

var App = Backbone.View.extend({

initialize: function()
{
this.collection = new Documents();
console.log("this.collection init", this.collection);
this.listenTo(this.collection, 'add', this.render);
this.listenTo(this.collection, 'sync', this.renderSidebarModels);
},

renderSidebarModels: function()
{
console.log("renderSidebarModels SYNC", this.collection);

for(var i=0; i<this.collection.length; i++)
{
console.log(this.collection.models);
this.sidebar = new SidebarView({model: this.collection.models[i]});
}
},

$( document ).ready(function() {
console.log( "ready!" );
var app = new App();
});

SidebarView.js

在 SidebarView.js 中,我从集合中获取所有模型。当我单击 id #titles 的按钮时,我会获取该用户的所有模型,而不仅仅是 this.model 上单击的模型。

var SidebarView = Backbone.View.extend({

el : this.$("#sidebar"),

template: _.template(this.$('#sidebar-template').html()),

events:
{
"click #titles": "open",
},

initialize: function()
{
console.log("sidebarView.initialize", this.model);
this.render();
},

render: function()
{

this.$el.append(this.template({ users: this.model }));
//console.log(this.model);
//return this;
},

open: function(e)
{
console.log("open.sidebarView", this.model);
},

})

最佳答案

您的方法不是初始化模型 View 的最干净的方法,因为您没有为每个模型初始化一个 View ,但是将 View 分配给模型的方式是遍历模型,并将每个集合项分配给特定 View 。这种方法很麻烦,会导致性能下降,还会导致在 View 中编写大量额外的代码。

最好的方法是使用每个模型一个 View ,这意味着我们集合中的每个模型都有自己的 View 对象来呈现该模式的数据。不过,这并不能消除对迭代集合并填充列表的 View 对象的需要。它仅将每个单独模型的实现移至该模型的 View 。通过这种方法,每个 View 都可以直接引用其模型。

类似这样的事情:

var App = Backbone.View.extend({    

initialize: function() {
this.collection = new Documents();
console.log("this.collection init", this.collection);
this.listenTo(this.collection, 'add', this.render);
this.listenTo(this.collection, 'sync', this.renderSidebarModels);
},

renderSidebarModels: function(item) {
this.collection.models.each(function(item) {
var sidebarView = new DealerView({
model : item
}, this);

sidebarView.render();
_this.$el.append(sidebarView.$el);
});
}
});

使用您的方法获取单击的项目的一种方法是使用适当的数据属性:

open: function(e){
e.preventDefault();
var id = $(e.currentTarget).data("id");
var item = this.collection.get(id);
console.log(item);
},

但正如我所说,这个解决方案不是最好的解决方案,我们被迫根据模型的 id 查找模型。

阅读本文以更好地理解:https://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/

关于javascript - 为什么我通过点击获得用户的所有模型而不是一键模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38480505/

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