Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to functions binded in events object in backbone.js

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?

like image 767
Gautham Renganathan Avatar asked Aug 01 '12 15:08

Gautham Renganathan


2 Answers

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
}
......
like image 38
Justin wong Avatar answered Oct 12 '22 05:10

Justin wong


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
    }
}
like image 81
Brendan Delumpa Avatar answered Oct 12 '22 07:10

Brendan Delumpa