簡體   English   中英

Ember.js-在控制器及其視圖之間進行通信

[英]Ember.js - Communicating between controllers and their views

我正處於學習Ember的初期階段,遇到了一些令人費解的事情。 我正在嘗試在兩個控制器之間進行通信,並讓它們的對應視圖也更新。

在簡化版本中,我想單擊一個按鈕以在一個控制器上觸發事件,從而在另一個控制器上啟動計時器。 可以,但是值更改時不會更新計時器的視圖。

這是我所擁有的:

var App = Ember.Application.create();

App.Route = Ember.Route.extend({
    events: {
        startTimer: function(data) {
          this.get('container').lookup('controller:Timer').start();
        }
    }
});

App.ApplicationController = Ember.Controller.extend({

    actionWord: 'Start',

    toggleTimer: function() {
        var timer = this.get('container').lookup('controller:Timer');

        if(timer.get('running')) {
            timer.stop();
        } else {
            timer.start();
            this.set('actionWord', 'Stop');
        }
    }
});

App.TimerController = Ember.Controller.extend({

    time: 0,
    running: false,
    timer: null,

    start: function() {
        var self = this;

        this.set('running', true);

        this.timer = window.setInterval(function() {
            self.set('time',  self.get('time') + 1);
            console.log(self.get('time'));
        }, 1000);
    },

    stop: function() {
        window.clearInterval(this.timer);
        this.set('running', false);
        this.set('time', 0);
    }

});

對於模板:

 <script type="text/x-handlebars">
    {{ render "timer" }}

    <button {{action toggleTimer }} >{{ actionWord }} timer</button>
</script>

<script type="text/x-handlebars" data-template-name="timer">
   {{ time }}
</script>

http://jsfiddle.net/mAqYR/1/

更新:

忘了提一下,如果您打開控制台,您會看到TimeController函數內部正在更新時間,只是時間沒有顯示在視圖中。

此外,直接在TimerController上調用start操作會正確更新視圖。

謝謝!

您使用的是Ember的過時版本。 我已經將您的小提琴更新為Ember rc3。 另外,我還用正確的方法替換了container.lookup實例。 container幾乎是一個私有對象。

http://jsfiddle.net/3bGN4/255/

window.App = Ember.Application.create();

App.Route = Ember.Route.extend({
    events: {
        startTimer: function(data) {
            this.controllerFor('timer').start();
        }
    }
});

App.ApplicationController = Ember.Controller.extend({
    actionWord: 'Start',
    needs: ["timer"],
    toggleTimer: function() {
        var timer = this.get('controllers.timer');
        if(timer.get('running')) {
            timer.stop();
        } else {
            timer.start();
            this.set('actionWord', 'Stop');
        }
    }
});

App.TimerController = Ember.Controller.extend({
    time: 0,
    running: false,
    timer: null,

    start: function() {
        var self = this;
        this.set('running', true);
        this.timer = window.setInterval(function() {
            self.set('time',  self.get('time') + 1);
            console.log(self.get('time'));
        }, 1000);
    },
    stop: function() {
        window.clearInterval(this.timer);
        this.set('running', false);
        this.set('time', 0);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM