Skip to content

Instantly share code, notes, and snippets.

@g00fy-
Created February 25, 2013 03:00
Show Gist options
  • Save g00fy-/5027167 to your computer and use it in GitHub Desktop.
Save g00fy-/5027167 to your computer and use it in GitHub Desktop.
lazyAttr helper for emberjs style template bindings (draft)
LazyAttribute = function(attribute,context){
this.attribute = attribute;
this.context = context;
this.id = _.uniqueId('h');
this.bindEvents();
};
LazyAttribute.prototype.bindEvents = function(){
this.context.on('change:'+this.attribute.split('.')[0],this.update,this);
};
LazyAttribute.prototype.update = function(){
this.val(this.getValue());
};
LazyAttribute.prototype.render = function(){
var startTag = '<script id="'+this.id+'start" type="text/helper"></script>';
var endTag = '<script id="'+this.id+'end" type="text/helper"></script>';
return startTag+this.getValue()+endTag;
};
LazyAttribute.prototype.getValue = function(){
var value=this.context;
_.each((this.attribute||'').split('.'),function(attr){
if(value){
value = value.get(attr) || value[attr];
}
});
if(_.isUndefined(value)){
value = ' ';
}
return value;
};
LazyAttribute.prototype.val = function(value){
var node = this.getNode();
if(arguments.length>=1){
node.textContent = value;
}
return node.textContent;
};
LazyAttribute.prototype.getNode = function(){
return this.startTag().nextSibling;
};
LazyAttribute.prototype.startTag = function(){
if(!this._startTag){
this._startTag = document.getElementById(this.id+'start');
}
return this._startTag;
};
LazyAttribute.prototype.endTag = function(){
if(!this._endTag){
this._endTag = document.getElementById(this.id+'end');
}
return this._endTag;
};
function helper(value){
var lazy = new LazyAttribute(value,this);
return lazy.render();
}
Marionette.ItemView.prototype.templateHelpers = function(){
var h = helper.bind(this.model);
return {
lazyAttr: h
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment