0

我正在将我的代码库从 EmberJS-1.0-rc1 升级到 EmberJS-1.0。

我的许多绑定似乎不再一致地同步了。语义一定已经改变了,但我不知道怎么做,或者我应该做什么!

var Widg = Ember.Object.extend({
    init: function () {
        this._super();

        console.log("aliasToValue is: ", this.get('aliasToValue'));
        if (this.get('aliasToValue') != this.get('value')) {
            throw "This exception doesn't get hit...";
        }

        console.log("Setting value to 'hello world'");
        this.set('value', "hello world");

        // I would expect:
        // this.get('value') == this.get('aliasToValue')
        // but that doesn't seem to work anymore....

        console.log("After settting, aliasToValue is: ", this.get('aliasToValue'));
        if (this.get('aliasToValue') != this.get('value')) {
            throw "Ugh, after setting, they don't match";
        }
    },
    value: "initial value",
    aliasToValueBinding: "value"
});

Widg.create(); // EXCEPTION: "Ugh, after setting, they don't match"
4

1 回答 1

0

当您添加 apropertyABinding: propertyB时,基本上 ember 创建一个观察者propertyA并在队列propertyB中安排同步(设置propertyAto的值,propertyB反之亦然) 。sync因为同步是计划好的,所以它会在运行循环结束时执行。所以,aliasToValue不要改变:

this.set('value', "hello world");
this.get('value'); // return "hello world"
this.get('aliasToValue'); // return "initial value"

您可以以编程方式调用刷新同步队列Ember.run.sync()。所以这将起作用:

this.set('value', "hello world");
this.get('value'); // return "hello world"
Ember.run.sync();   // don't wait for the end of runloop, and make the sync here
this.get('aliasToValue'); // return "hello world"

但是对于您的示例中的这项工作,您需要进行一些更改。在您的情况下,您正在设置init函数中的属性。但是在 init 函数中,没有触发观察。因此,不会安排同步。您可以使用on('init')来在对象初始化时对其进行更改:

...
didInit: function() {
   // now the observes will trigger when a property change
}.on('init')
...

您更新的代码将如下所示:

//the application
App = Ember.Application.create();

App.MyObject = Ember.Object.extend({
    didInit: function () {

        console.log("aliasToValue is: ", this.get('aliasToValue'));
        if (this.get('aliasToValue') != this.get('value')) {
            alert( "This exception doesn't get hit..." );
        }

        console.log("Setting value to 'hello world'");
        this.set('value', "hello world");

        // I would expect:
        // this.get('value') == this.get('aliasToValue')
        // but that doesn't seem to work anymore....

        console.log("After settting, aliasToValue is: ", this.get('aliasToValue'));
        Ember.run.sync();
        if (this.get('aliasToValue') != this.get('value')) {
            alert( "Ugh, after setting, they don't match" );
        }
    }.on('init'),
    value: "initial value",
    aliasToValueBinding: "value"
});

App.MyObject.create(); // EXCEPTION: "Ugh, after setting, they don't match"

和 jsfiddle http://jsfiddle.net/marciojunior/Bk7L9/

当然,这Ember.run.sync()只是在极少数情况下使用,删除它会使你的模板和属性被更新,但是当 runloop 完成时。我用它让你看到绑定的属性立即更新。

有关 runloop 的更多信息,请参阅此答案What is Ember RunLoop 以及它是如何工作的?

于 2013-09-11T00:50:08.083 回答