Search code examples
javascriptbackbone.jsbackbone-views

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?


Solution

  • 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
        }
    }