Trigger Actions Mixin

by ethan_selzer

HTML

<script type="text/x-handlebars" id="index">

    {{#view ActionSender
        clickAction="viewWasClicked"}}

        click me

    {{/view}}

    {{#view ActionSender
        mouseEnterAction="didStartHover"
        mouseLeaveAction="didEndHover"}}
    
        <span {{bindAttr class="isHovering:hover"}}>
            hover me
        </span>

    {{/view}}
    
</script>

CSS

.hover { color: red }

JavaScript

$.getScript( 'https://raw.github.com/wycats/handlebars.js/1.0.0-rc.3/dist/handlebars.js', function(){
    $.getScript( 'https://raw.github.com/emberjs/ember.js/release-builds/ember-1.0.0-rc.1.js', function(){
        
        var TriggerActions = Ember.Mixin.create({
            has : function( name ){
                return this._super.apply( this, arguments ) || this.hasAction( name );
            },
            hasAction : function( name ){
                var a = this.get( name+'Action' );
                return !!( a );
            },
            trigger : function(){
                this.sendAction.apply( this, arguments );
                return this._super.apply( this, arguments );
            },
            sendAction : function( name, args ){
                var controller = this.get( 'controller' );
                var action = this.get( name+'Action' );
                if( controller && action ){
                    args = [].slice.call( arguments );
                    args[0] = action;
                    args.push( this );
                    return controller.send.apply( controller, args );
                }
            }
        });
        
        window.ActionSender = Ember.View.extend( TriggerActions );
        
        var App = Ember.Application.create();
        
        App.IndexController = Ember.Controller.extend({
            viewWasClicked : function(){
                alert( 'the view was clicked' );
            },
            didStartHover : function(){
                this.set( 'isHovering', true );
            },
            didEndHover : function(){
                this.set( 'isHovering', false );
            }
        });
    
    });
});