How to handle events of objects outside of a View in backbone.js?
-
30-10-2019 - |
Question
As in the backbone-todolist example,I have a collection of elements. I made 2 views, one for the list and one for each element. It works great.
However, as I need the elements of the list to be modified, in the view of the element I handle the modify event opening a popup with the colorbox plugin which contains an html form. The html is dynamically created and passed to the colorbox element.
I use colorbox and backbone-form additional plugins.
Now: the popup IS NOT A CHILD (in the DOM) of my view, so I don't know how to fire the event on the 'button submit' action.
Here is a snippet of the code (omitted unuseful parts):
// ** view of the single collection element
window.listElement = Backbone.View.extend({
tagName: 'li',
[...]
updateElement:function(){
//creates the update form in a popup menu
var form=new Backbone.Form({BLA BLA BLA...I TESTED IT, IT WORKS.
}).render();
$(form.el).append('<input id="update-btn" type="button" name="updateBtn" value="Update" style="display: block;">');
self=this;
//HERE COME THE TROUBLES
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
}).delegate('#update-btn','click',self.saveEl());
},
saveEl:function(){
console.log("now saving..")},
},
What happens is that the saveEl method (or function?, which term would be more correct?) is fired when the popup is opened.
I also tried with a different version of the code:
initialize: function(){//added this in the initialize function
_.bindAll(this, "saveEl");
$('#update-btn').bind('click', this.saveEl());
},
updateElement:function(){
//LIKE BEFORE BUT WITHOUT DELEGATE FUNCTION
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
});
},
saveEl:function(){
console.log("now saving..")},
},
In this second case, the saveEl function is called when the view is created (thus one time for each element of the list).
I know that I colud make a view for the popup, but somEthing says me that it's too complicated and that there should me a more simple architecture.
The question, indeed, is more general: is it possible to handle events fired by DOM object outside the scope of $(this.el) without creating a view for them?
thanks in advance.
-----------------UPDATE:--------------
The final version of working code is the following:
// ** view of the single collection element
window.listElement = Backbone.View.extend({
tagName: 'li',
[...]
updateElement:function(){
//creates the update form in a popup menu
var form=new Backbone.Form({BLA BLA BLA...I TESTED IT, IT WORKS.
}).render();
$(form.el).append('<input id="update-btn" type="button" name="updateBtn" value="Update" style="display: block;">');
$(form.el).delegate('#update-btn','click',this.saveEl())
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
});
},
saveEl:function(){
console.log("now saving..")},
}
});
No correct solution