gpt4 book ai didi

javascript - 使用 Backbone.js 从列表中选择元素

转载 作者:行者123 更新时间:2023-11-30 17:55:03 28 4
gpt4 key购买 nike

这是一个非常笼统的问题,如果您希望我详细说明,请告诉我。我有一个元素列表,每个元素都由一个 View 呈现。单击某个元素时,它会突出显示,负责该元素的 View 将其模型发送到单独的 View ,该 View 显示与该元素相关的附加信息。

我正在尝试为用户实现使用箭头键在元素之间切换的功能,但我不确定该怎么做。

这是我的 View 的代码:

var app = app || {};

app.EmployeeView = Backbone.View.extend({
tagName: 'li',
className: 'list-group-item',
template: _.template('<%= Name %>'),
render: function() {
var html = this.template(this.model.attributes);
this.$el.html(html);
},
events: {
"mouseover" : function() {
this.$el.addClass('highlighted');

},
"mouseout" : function() {
this.$el.removeClass('highlighted');
},
"click" : function() {
$('.selected').removeClass('selected');
this.$el.addClass('selected');
$(document).trigger('select', [this.model]);
},
},
});

有人对我如何使用箭头键触发适当的 View 以转发其模型有任何建议吗?

最佳答案

我有一个非常相似的功能要为我的产品实现。我有一个图像列表。用户单击一个缩略图并可视化全尺寸图像。在那里,我还有一个显示图片信息的详细信息框,我希望用户在保持全尺寸 View 的同时使用箭头键浏览图片。我还有“上一个”和“下一个”按钮,它们的作用应该是一样的。我认为结果很干净,这就是我所做的:

SingleEntryView = Backbone.View.extend({

initialize : function() {

// Here I save a reference to the currentIndex by getting the index
// of the current model within the collection.
this.currentIndex = this.collection.indexOf(this.model);

// Important: here I attach the keydown event to the whole document,
// so that the user doesn't necessarily have to focus the view's
// element to use the arrows.
$document.on('keydown.singleEntry', this.onKeyDown.bind(this));

},

// Having attached the keydown event to document, there's no autocleaning.
// Overriding remove to detach the listener when the view goes away.
remove : function() {

$document.off('.singleEntry');

Backbone.View.prototype.remove.call(this);

},

// Keydown listener. Interested only in arrow keys.
onKeyDown : function(e) {

if (e.keyCode == 37) // left arrow
this.prev();
else if (e.keyCode == 39) // right arrow
this.next();

return true;

},

// Click events on the prev/next buttons (they behave == to the arrow keys)
events : {
'click #prev' : 'prev',
'click #next' : 'next'
},

// Handlers shared by both prev/next buttons and arrow keys.
// What is the current index? Go to the prev/next one.
// If we are at the start/end, wrap around and go to the last/first.
prev : function() {
this.goTo(this.currentIndex > 0 ? this.currentIndex - 1 : this.collection.length - 1);
return false;
},

next : function() {
this.goTo(this.currentIndex < this.collection.length - 1 ? this.currentIndex + 1 : 0);
return false;
},

goTo : function(i) {

this.model = this.collection.at(i);
this.currentIndex = i;

// App is my Router
App.navigate('app/boards/' + this.collection.id + '/entries/' + this.model.id, {
trigger: true
});

}

}

关于javascript - 使用 Backbone.js 从列表中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221535/

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