here is my scenario of backbone view
var TreeNode = Backbone.View.extend({
tagName : "span",
className : "ndelem dirnode",
events : {
"click" : "selectNode",
},
initialize : function() {
_.bindAll(this, "render", "selectNode");
$(this.el).append(this.model.get("fname")).attr({
"data-cid" : this.model.cid
});
},
render : function() {
this.delegateEvents();
return this;
},
selectNode : function(e) {
e.stopPropagation();
this.model.set({
isOpened : true
});
}
});
Main view
var TreeZone = Backbone.View.extend({
el : $("#nodes"),
initialize : function() {
this.collection.bind("add", this.list, this);
},
getHtml : function(elem) {
var newItem = $("<div/>").append(elem);
return newItem.html();
newItem.remove();
},
getSelectedItem : function() {
var selectedItem = $('#nodes').jqxTree('selectedItem');
if (selectedItem != null)
return selectedItem.element;
else {
var treeItems = $('#nodes').jqxTree('getItems');
var firstItem = treeItems[0];
return firstItem.element;
}
},
list : function(file) {
var node = new TreeNode({
model : file
});
var newItem = this.getHtml(node.render().el);
var element = this.getSelectedItem();
$('#nodes').jqxTree('addTo', {
html : newItem,
}, element);
$('#nodes').jqxTree('expandItem', element);
}
});
var tree = new TreeZone({collection:dircollection});
I adding elements to the collection.
but tree node click event not firing. simply I am adding raw html to the tree node because tree doesnt support jquery object. so I am trying get html from get html function. and giving it to tree.
Events are bound to DOM elements but you end up working with HTML strings. You’re doing this:
So
getHTMLreturns a string and as soon as you convert yourTreeNode‘sel(which is a DOM object) to a string, thedelegatewhich Back attaches toelfor event handling is gone: nodelegate, no events.I can see a couple options:
<span>out of#nodesafter theaddTocall and usesetElementto re-attach it to theTreeNodeview.Rearrange the structure so that you don’t have
TreeNodeat all. If you attach a class to the node<span>s then you could letTreeZonedeal with all the events; for example, if you used<span class="node">for the nodes, thenTreeZonecould have this:And you’d have a
selectNodemethod onTreeZoneinstead ofTreeNode. You might need to add adata-idattribute to the<span>s so that you can backtrack from the<span>to the model.Also, note that your
newItem.remove();ingetHtmlwill never be executed.