I need to have arguments to the functions used in the events object in Backbone.
var DocumentRow = Backbone.View.extend({
tagName: "li",
className: "document-row",
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
},
render: function () {
// do something
}
});
Now let the definition of open be:
function open(id) {
if (id) {
// do something
} else {
// do something else
}
}
I will call open from another function and will pass id when I call it. So based on whether I pass id or not I need to do different things. How do I do this in Backbone? Currently, id when called via click I expect it to be undefined. But an event object is passed.
Why does this happend and how can I pass an argument?
you can see here: http://backbonejs.org/docs/backbone.html#section-156
The most critical sentence is:
this.$el.delegate(selector, eventName, method);
because backbone's events is jquery's delegate( http://api.jquery.com/delegate/ ),so the parameter is passed just is jquery's delegate default parameters passed.
you can update your code like this:
......
open : function(event) {
//get id from event
var id = event.xxx ;//pseudo code
if (id) {
this.openid(id);
} else {
// do something else
}
},
//your another function direct call openid
openid: function(id){
// do something
}
......
Another way to approach this is to use a completely different method that handles the click, and calls "open" so it can be called by another process. As another person mentioned, methods you specify in the events hash are jquery delegate wrappers, so there's not much you can do with respect to params as what you'll get is what delegate provides. So in that case, create another method that does the actual icon click that will invoke open:
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
},
/**
* Specifically handles the click and invokes open
*/
handleIconClick : function(event) {
// ...process 'event' and create params here...
this.open(params);
},
/**
* This can be called remotely
*/
open : function(id) {
if (id) {
// do something
} else {
// do something else
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With