How to handle click events of similar but different views?
I'm trying to implement a simple toolbar using Backbone.js. I have the following simple Backbone code:
var Toolbox = Backbone.View.extend({
el: $("#toolbox ul"),
initialize : function() {
_.bindAll(this, "addOne");
toolCollection.each(this.addOne);
},
addOne : function(tool) {
var view = new ToolView({ model: tool });
$(this.el).append(view.render().el);
}
});
// Tool model and collections
var Tool = Backbone.Model.extend();
var toolCollection = new Backbone.Collection([
new Tool({
tool: "toolName1"
}),
new Tool({
tool: "toolName2"
})
]);
// The view of the individual tools
var ToolView = Backbone.View.extend({
tagName: "li",
template : _.template开发者_Python百科($("#tool-template").html()),
events: {
"click #toolbox ul li a": "toolClick"
},
initialize : function() {
_.bindAll(this, "render", "toolClick");
this.model.view = this;
},
render : function() {
var mj = this.model.toJSON();
$(this.el).html(this.template(mj));
return this;
},
toolClick : function() {
console.log("Tool clicked");
}
});
var tb = new Toolbox;
So, with this, I have a question. I obviously need to handle each click on a tool differently. When I instantiate my view, can I bind a specific click event to handle the click of that specific tool, and if so, where would I write the click event at? I'm not even sure if I'm missing something here, but could anyone suggest a pattern of how I can have a group of related, but different views and how to handle the click of view separately? Any help would be appreciated. Thanks in advance.
I hope I understood you right.
You have a toolbox with different tools. And of course you have to handle clicks on different tools differently.
So, why don't you have all the click events in the ToolBox view with IDs attached to the tools.
events: {
"click #toolbox #zoom": "zoomClick",
"click #toolbox #pen": "penClick",
"click #toolbox #line": "lineClick"
}
You can have the tools created in the ToolBox render() function. Hope that helps.
Another way to handle this. You are already capturing the click on the individual tools and passing it to the toolclick function. The function is aware of the model that was clicked you could just pass it to a switch statement to create your separate behavior.
toolClick: function() {
var toolname = this.model.get("tool");
switch(toolname) {
case "toolName1":
//Do something;
break;
case "toolName2":
//Do something else;
break;
}
}
This way you don't have to do a bunch of prep in render or templates.
If your tool is the same but does something different than the other tools, then you need to create that separate tool by extending your "vanilla" tool. With extend you can either add new properties and functions or override them entirely.
var ExtendedToolView = ToolView.extend({
toolClick: function() {
console.log("Extended Tool clicked");
}
});
精彩评论