菜鸟在这里学习backbone.js。我试图创建一个简单的水平菜单(每个菜单项都是一个模型,整个菜单是一个集合)。我想知道单击了哪个菜单项。在 menuItemView 中,我将“click a”事件绑定到“clicked”函数,但是当我单击时它不会触发。我找到的最接近的解决方案是:http: //lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/我试图复制类似的功能......即使我认为我已经复制了几乎相同的功能,但我似乎仍然无法让它工作。我确实浏览了所有似乎解决检测哪个模型/项目被点击的问题的帖子,但它们似乎都没有帮助。任何帮助,将不胜感激。我知道在简单的 jquery 中,一个可点击的菜单和获取它的 id 可能要简单得多,但我想我会以此为例来学习主干。
HTML
<header>
<ul id="nav">
</ul>
</header>
JAVASCRIPT
(function($) {
window.app = window.app || {};
//Goal:if selected=true, menu item should be highlighted
MenuItem = Backbone.Model.extend({
label: "Default Label",
selected: false,
id: 0
});
MenuList = Backbone.Collection.extend({
model: MenuItem,
initialize: function(models, options) {
//nothing ... yet
}
});
//View for a single item. Returns el that looks like:
// <li id='4' class='false'><a href='#4'> Item 4 </a> </li?
MenuItemView = Backbone.View.extend({
tagName: "li",
render: function() {
var id = this.model.get("id");
var cls = this.model.get("selected");
var lbl = this.model.get("label");
$(this.el).attr('id', id).addClass(cls.toString());
$(this.el).html("<a href=#" + id + " >" + lbl + "</a> </li>");
return this; //recommended as this enables calls to be chained.
},
events: {
"click a": "clicked" //Firebug shows 'a' element bound to
//native 'click' and not 'clicked'. WHY?
},
clicked: function(ev){
alert($(ev.target).text()); //NOT HAPPENING :-(
//do something to highlight menu item via css stuff.
}
});
MenuListView = Backbone.View.extend({
el: $("header > ul"),
initialize: function() {
this.menulist = new MenuList(null, { view: this });
_.bindAll(this, "renderItem");
},
renderItem: function(model) {
var menuitemView = new MenuItemView({ model: model });
menuitemView.render();
$(this.el).append(menuitemView.el);
},
render: function() {
this.collection.each(this.renderItem);
},
setActivePage: function(ev) {
alert($(ev.target).text());
window.app.footerview.updatePageNumber(10);
}
});
var items = new MenuList([
{id: 1, label: "item 1", selected: true},
{id: 2,label: "item 2",selected: false},
{id: 3,label: "item 3",selected: false},
{id: 4,label: "item 4",selected: false}
]);
window.app.menuview = new MenuListView({ collection: items });
window.app.menuview.render();
$("header").html(window.app.menuview.el);
})(jQuery);
运行示例可以在 jsfiddle 上看到:.. 见http://jsfiddle.net/gopal_a/4uzcb/3/