Ember.js中的Subscriber/Observer模式

Subscriber/Observer pattern in Ember.js

本文关键字:Observer 模式 Subscriber js 中的 Ember      更新时间:2023-09-26

是否可以在Ember.js中使用subscriber/observer模式?例如,视图A和视图B都侦听模型C内部的更改。这需要模型C能够触发自定义事件。我一直在想如何在Ember.js中创建一个模型触发事件,但到目前为止没有成功。

我相信您正在寻找的功能在Ember.js.中被称为"绑定"

主页上有很多例子描述了如何按照你的建议行事,但这里有一个简短的回顾:

window.MyApp = Ember.Application.create();
MyApp.MyModel = Ember.Object.create({
  myProperty: "Hello World!",
  goodbye: function() {
    this.set("myProperty", "Goodbye!");
  })
});
MyApp.modelInstance = MyApp.MyModel.create();

现在在<body>标签中创建两个视图:

<script type="text/x-handlebars">
  View1: <b>{{MyApp.modelInstance.myProperty}}</b>
</script>
<script type="text/x-handlebars">
  View2: <b>{{MyApp.modelInstance.myProperty}}</b>
</script>

现在,页面应该进行渲染,您将看到两个视图都显示"Hello World!"。打开控制台并键入

MyApp.modelInstance.goodbye();

你会看到你的观点改变,说"再见!"。

视图通过使用双大括号自动创建到MyApp.modelInstance.myProperty的绑定,但您可以通过多种方式创建绑定。每当myProperty的值发生更改时,所有绑定都将自动更新。但是,请注意,您必须调用set("myProperty", "something new"),以便Ember知道为您更新绑定;如果你只说myProperty = "something new",它不会触发任何更改事件。

至少在Sproutcore中,这就是绑定的用途。

如果你有一个型号

App.Person = SC.Object.extend({
   name: 'Bruce Banner'
});

然后你就会有一个像这样的控制器

App.personController = SC.ObjectController.create();

然后,您可以在控制器上设置内容

App.personController.set('content', somePerson);

现在,任何视图都可以绑定到模型对象上的数据。

SC.LabelView = SC.LabelView.extend({
...
    valueBinding: 'App.personController.name'
})

因此,如果你更改名称

somePerson.set('name', 'Chris');

视图将自动更新。