Reputation: 5638
Is it possible to use the subscriber/observer pattern in 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. I've been trying to figure out how to make a model trigger event in Ember.js but no luck so far.
Upvotes: 1
Views: 1115
Reputation: 20667
I believe the feature you are looking for is called "Bindings" in 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:
<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!". 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. Whenever the value of myProperty
changes, all of the bindings will be automatically updated. Note, however, that you must call set("myProperty", "something new")
so that Ember knows to update the bindings for you; it won't fire any change events if you just say myProperty = "something new"
.
Upvotes: 3
Reputation: 120198
At least in Sproutcore, that is what bindings are for.
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.
Upvotes: 0