Created
May 6, 2012 01:48
-
-
Save kbullaughey/2606979 to your computer and use it in GitHub Desktop.
Example of creating binding-like observers that are view-instance specific.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/x-handlebars"> | |
{{#each App.aController}} | |
{{#view App.MyView contentBinding="this"}} | |
{{id}} says {{stub}} | |
{{/view}} | |
{{/each}} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Gist relates to this question on Stackoverflow: http://stackoverflow.com/posts/10406771