Search code examples
javascriptbackbone.jsmarionette

@ symbol in object key


I don't know the proper place to post this question but I was reading the Marionette docs and saw the following code when describing

Marionette.Behaviors:

var MyView = Marionette.ItemView.extend({
    ui: {
        "destroy": ".destroy-btn"
    },

    events: {
        "click @ui.destroy": "warnBeforeDestroy"
    }

I have never seen an @ symbol in an object key before. Does the @ mean anything or is it just part of the string and does nothing special?


Solution

  • TL;DR The string starting with the @ symbol in the property name of an events object in a Backbone.Marionette view is parsed by Marionette. Marionette will match the string after @ui. and replace it with the corresponding value in that view's ui hash. In your example, "click @ui.destroy" becomes "click .destroy-btn".


    Marionette ui

    Marionette was enhanced with a little syntactic sugar to help you better organize the DOM dependencies in your view. In other words, marionette views can make use of an ui hash in your view that holds references to DOM elements inside that view's el. In your example you set

    ui: {
      "destroy": ".destroy-btn"
    }
    

    This assumes that your view template will have at least one element with class .destroy-btn. After your view is rendered, Marionette will call view.bindUIElementsand each member of your ui hash will be populated with the jQuery object that represents the element(s) that match the selector passed in to the ui object.

    Thus, in your view, this.ui.destroy will return the jQuery object for the selector .destroy-btn inside your view's el.

    Marionette parses the events hash

    The other thing Marionette will do for you, and this is where your question comes in, is parse your events hash. If it finds any events properties that include an @ui. prefix it will capture the string after the . and return the selector stored in your ui hash.

    So, if you have

    events: {
      "click @ui.destroy": "warnBeforeDestroy"
    }
    

    Marionette will hand Backbone an events hash that looks like:

    events: {
      "click .destroy-btn": "warnBeforeDestroy"
    }
    

    Further reference

    See Marionette events and bindUIElements