Skip to content

Instantly share code, notes, and snippets.

@kbullaughey
Created May 6, 2012 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbullaughey/2606979 to your computer and use it in GitHub Desktop.
Save kbullaughey/2606979 to your computer and use it in GitHub Desktop.
Example of creating binding-like observers that are view-instance specific.
App.hash = Ember.Object.create();
App.theList = [{id: 'item1', value: 1}, {id: 'item2', value: 2}, {id: 'item1', value: 1}];
App.aController = Ember.ArrayController.create();
App.aController.set('content', App.theList);
App.MyView = Ember.View.extend({
hashBinding: "App.hash",
stub: function(key, val) {
var id = this.get('id');
if (id) {
if (arguments.length === 1) {
return this.get('hash').get(id);
} else {
this.get('hash').set(id, val);
}
}
}.property('hash', 'id').cacheable(),
id: function() {
var c = this.get('content');
if (c) {
return c.id;
}
}.property('content').cacheable(),
contentWillChange: function() {
var id = this.get('id');
if (id) {
this.removeObserver('hash.' + id, this, 'stubDidChange');
}
}.observesBefore('content'),
contentDidChange: function() {
var id = this.get('id');
if (id) {
var c = this.get('content');
this.set('stub', c.value);
this.addObserver('hash.' + this.get('id'), this, 'stubDidChange');
this.stubDidChange();
}
}.observes('content'),
stubDidChange: function() {
this.notifyPropertyChange('stub');
},
click: function() {
var id = this.get('id');
var h = this.get('hash');
var val = h.get(id);
h.set(id, val+1);
}
});
<script type="text/x-handlebars">
{{#each App.aController}}
{{#view App.MyView contentBinding="this"}}
{{id}} says {{stub}}
{{/view}}
{{/each}}
</script>
@kbullaughey
Copy link
Author

This Gist relates to this question on Stackoverflow: http://stackoverflow.com/posts/10406771

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment