Skip to content

Instantly share code, notes, and snippets.

@StevenLangbroek
Last active September 20, 2016 08:22
Show Gist options
  • Save StevenLangbroek/6bd28d8201839434b843 to your computer and use it in GitHub Desktop.
Save StevenLangbroek/6bd28d8201839434b843 to your computer and use it in GitHub Desktop.
Backbone with decorators (warning: untested) *update*: corrections from Ben applied.
import _ from 'underscore';
export function on(eventName){
return function(target, name, descriptor){
if(!target.events) {
target.events = {};
}
if(_.isFunction(target.events)) {
throw new Error('The on decorator is not compatible with an events method');
return;
}
if(!eventName) {
throw new Error('The on decorator requires an eventName argument');
}
target.events[eventName] = name;
return descriptor;
}
}
import { ItemView } from 'backbone.marionette';
import { on } from '../utils/decorators';
import FormTemplate from '../templates/FormTemplate';
class FormView extends ItemView {
static template = FormTemplate;
@on("click .button")
submitForm(e){
e.preventDefault();
console.log("I'm a teapot!");
}
}
@benmccormick
Copy link

@StevenLangbroek this is still awesome. I tested it though, and it doesn't look like it works exactly like this. The constructor hasn't run when decorators are evaluated, which causes issues for delegateEvents (which needs an $el value.

I wrote an alternative version that is a bit more verbose, but is working for me:

export function on(eventName){
  return function(target, name, descriptor){
    if(!target.events) {
        target.events = {};
    }
    if(_.isFunction(target.events)) {
        throw new Error('The on decorator is not compatible with an events method');
        return;
    }
    if(!eventName) {
        throw new Error('The on decorator requires an eventName argument');
    }
    target.events[eventName] = name;
    return descriptor;
  }
}

I can just use the events hash since it won't have been evaluated yet. This does make this incompatible with events functions, but I don't think you'd want to mix the decorators syntax with an events function anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment