处理Ember中的操作中的事件绑定和回调

时间:2013-11-29 17:33:44

标签: javascript ember.js

这闻起来。此操作的结果应该在页面上注册事件处理程序,但是我应该将命名函数回调(clickHandler)?混合?或者完全是另一个班级。

App.StepController = Ember.ObjectController.extend({
    actions: {
        captureStep: function() {

            //Bind the handler to this so callback has access to Controller properties
            var clickHandler = clickHandler.bind(this);

            //Can't do this with jquery, as capture is not cross browser compatible.
            //Setting capture to true on a body event makes this event fire before all others                
            if (document.body.addEventListener) {
                document.body.addEventListener('click', clickHandler, true);
            }

            function clickHandler(event) {
                event.preventDefault(); //Needed for links/buttons
                event.stopImmediatePropagation(); //Stop the event from bubbling and prevent 'same element' event handlers 

                //Determine clickTarget...

                console.log("Clicked: " +  clickTarget);
                this.set('model.targetPath', clickTarget);

                // remove this handler from the body
                document.body.removeEventListener(event.type, clickHandler, true);
            }
        }
    }
});

1 个答案:

答案 0 :(得分:1)

Ember views will handle the page events为你服务;无需编写自己的事件处理程序:

App.StepView = Ember.View.extend({
    click: function(event) {
           this.get('controller').set(...);
        }
    }
});

或者,您可以使用links或操作actions来处理点击事件。