Skip to content

Instantly share code, notes, and snippets.

@kuon
Created January 24, 2011 11:47
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 kuon/793120 to your computer and use it in GitHub Desktop.
Save kuon/793120 to your computer and use it in GitHub Desktop.
SG.SelectView = SC.View.extend({
displayProperties:['items', 'itemTitleKey', 'itemValueKey'],
tagName:"select",
render:function(ctx, first) {
ctx.addClass('sg-select');
if(!this.get('isEnabled')) {
ctx.attr('disabled','disabled');
ctx.addClass('disabled');
return;
}
var items = this.get('items');
if(!items) return;
var itemValueKey = this.get('itemValueKey');
var itemTitleKey = this.get('itemTitleKey');
this._firstValue = null;
items.forEach(function(item) {
var value = GN.serializeObject(item, itemValueKey);
var title = GN.serializeObject(item, itemTitleKey);
this._firstValue = this._firstValue || value;
ctx.push('<option value="'+value+'">'+title+'</option>');
}, this);
},
_valueDidChange:function() {
if(this._updatingValue || !this.get('isEnabled')) return;
var value = this.get('value');
this._updatingValue = YES;
SC.RunLoop.begin();
if(!value) {
this.setIfChanged('value', this._firstValue);
value = this.get('value');
}
this.$().val(value);
SC.RunLoop.end();
this._updatingValue = NO;
}.observes('value'),
_fieldValueDidChange:function() {
this.setIfChanged('value', this.$().val());
},
_syncFirstValue:function() {
var value = this.get('value');
if(!value) {
this.setIfChanged('value', this._firstValue);
}
},
didCreateLayer: function() {
sc_super();
SC.Event.add(this.$(), 'change', this, '_fieldValueDidChange') ;
},
willDestroyLayer: function() {
SC.Event.remove(this.$(), 'change', this, '_fieldValueDidChange');
},
_itemsDidChange:function() {
this.set('layerNeedsUpdate', YES);
}.observes('*items.[]')
});
@kuon
Copy link
Author

kuon commented Jan 24, 2011

GN.serializeObject = function (v, k) {
  if(!v) return '';
  if(typeof(v) !== 'object') return v.toString();
  if(v.get) {
    if(k) return v.get(k);
    if(v.get('isRecord')) return v.get('id');
    return SC.guidFor(v);
  }
  if(k) return v[k];
  return v.toString();
};

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