fedoroffn
fedoroffn

Reputation: 427

Ember incementProperty on an interval

Two-part problem:

First part

I have a "seconds" (as in time) property that I want to increment with two different events on the same element:

  1. Click to increment
  2. Click-and-hold (mousedown) to increment every 1/10th second.

From what I've read, the best way to get two events on the same element is to create a component and use the built-in event handlers. So I've done that, BUT using a setInterval in my mousedown event creates a scoping issue where 'this' becomes the window and incrementProperty can no longer access its model.

Here's my component code. The click event works beautifully (without the mousedown).

App.PaceAdjustUpComponent = Ember.Component.extend({
    click: function() {
        var ps = this.get('model.ps'),
            pm = this.get('model.pm');
        this.incrementProperty('ps');
        this.send('calculateTime');
        if (ps >= 59) {
            this.incrementProperty('pm');
            this.set('model.ps', 0);
        }
    },
    mouseDown: function() {
        var interval;
        var ps = this.get('model.ps'),
            pm = this.get('model.pm');
        interval = window.setInterval(function() {
            ps + 1;
            this.send('calculateTime');
            if (ps >= 59) {
                this.incrementProperty('pm');
                this.set('model.ps', 0);
            }
        }, 100);
    },
    mouseUp: function() {
        window.clearInterval(interval);
    }
    });

Second Part:

This

        this.send('calculateTime');

was originally part of some code in a controller, and there it worked fine, but I need to be able to send that method to the controller so that when my incrementer works, it also fires 'calculateTime'.

I'm a noob. Totally green. Need lots of hand-holding. Thanks.

Upvotes: 1

Views: 322

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

You're essentially out of scope. And if you want to send an action out of a component you need to hook it up while creating the component and use sendAction instead of send (sendAction will send the action to the hooked up action name used while creating the component)

{{pace-adjust-up model=model calculateTime='calculateFooooo'}}

App.PaceAdjustUpComponent = Ember.Component.extend({
  click: function() {
    this.increment();  
  },
  mouseDown: function() {
    var interval, self = this;
    interval = window.setInterval(function() {
      self.increment();
    }, 100);
    this.set('interval', interval);
  },
  mouseUp: function() {
    window.clearInterval(this.get('interval'));
  },
  increment: function(){
    var ps = this.get('model.ps'),
        pm = this.get('model.pm');
    this.incrementProperty('model.ps');
    this.sendAction('calculateTime');
    if (ps >= 59) {
      this.incrementProperty('model.pm');
      this.set('model.ps', 0);
    }
  }
});

http://emberjs.jsbin.com/qitohavu/1/edit

Upvotes: 1

Related Questions