简体   繁体   English

Ember.js中的订阅者/观察者模式

[英]Subscriber/Observer pattern in Ember.js

Is it possible to use the subscriber/observer pattern in Ember.js? 是否可以在Ember.js中使用订户/观察者模式? For example, view A and view B both listens to changes inside a model C. This requires model C to be able to trigger custom events. 例如,视图A和视图B都侦听模型C内的更改。这要求模型C能够触发自定义事件。 I've been trying to figure out how to make a model trigger event in Ember.js but no luck so far. 我一直试图弄清楚如何在Ember.js中制作一个模型触发事件,但到目前为止还没有运气。

I believe the feature you are looking for is called "Bindings" in Ember.js. 我相信您正在寻找的功能在Ember.js中称为“绑定”。

There are tons of examples on the homepage that describe how to do what you are suggesting, but here is a quick recap: 主页上有大量的例子描述了如何做你的建议,但这里有一个简短的回顾:

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

MyApp.MyModel = Ember.Object.create({
  myProperty: "Hello World!",

  goodbye: function() {
    this.set("myProperty", "Goodbye!");
  })
});

MyApp.modelInstance = MyApp.MyModel.create();

Now create your two views inside your <body> tag: 现在,在您的<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>

Now the page should render and you'll see both views say "Hello World!". 现在页面应该渲染,你会看到两个视图都说“Hello World!”。 Open up the console and type 打开控制台并键入

MyApp.modelInstance.goodbye();

And you'll see your views change to say "Goodbye!". 而且您会看到您的观点变为“再见!”。

The views automatically create Bindings to MyApp.modelInstance.myProperty by using the double curly braces, but you can create bindings in a variety of ways. 视图通过使用双花括号自动创建到MyApp.modelInstance.myProperty的Bindings,但您可以通过各种方式创建绑定。 Whenever the value of myProperty changes, all of the bindings will be automatically updated. 每当myProperty的值发生变化时,所有绑定都将自动更新。 Note, however, that you must call set("myProperty", "something new") so that Ember knows to update the bindings for you; 但是请注意,您必须调用set("myProperty", "something new")以便Ember知道为您更新绑定。 it won't fire any change events if you just say myProperty = "something new" . 如果你只是说myProperty = "something new"它不会触发任何变化事件。

At least in Sproutcore, that is what bindings are for. 至少在Sproutcore中,这就是绑定的目的。

If you have a model 如果你有模特

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

You would then have a controller such as 然后,您将拥有一个控制器,例如

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

You could then set the content on the controller 然后,您可以在控制器上设置内容

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

Now, any view can bind to the data on the model object. 现在,任何视图都可以绑定到模型对象上的数据。

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

So if you ever change the name 所以如果你改名字的话

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

The view will update automatically. 视图将自动更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM