Last active
September 20, 2016 08:22
-
-
Save StevenLangbroek/6bd28d8201839434b843 to your computer and use it in GitHub Desktop.
Backbone with decorators (warning: untested) *update*: corrections from Ben applied.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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:
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.