Skip to content

Instantly share code, notes, and snippets.

@jwestbrook
Created March 18, 2014 03:17
Show Gist options
  • Save jwestbrook/9612925 to your computer and use it in GitHub Desktop.
Save jwestbrook/9612925 to your computer and use it in GitHub Desktop.
var BackboneAdapterMethods = {
hide : function(){
this.invoke('hide');
},
attr : function(map){
this.invoke('writeAttribute',map);
},
text: function() {
var text = this.map(function(item){
return item.innerText != undefined ? item.innerText : item.innerHTML.stripTags();
});
return text.join(' ');
},
html : function(html){
this.invoke('update',html);
},
remove : function(){
this.invoke('remove');
},
find: function(selector) {
var elements = [];
this.each(function(item){
elements.concat(item.select(selector));
});
return elements;
}
};
Object.extend(Array.prototype,BackboneAdapterMethods);
var BackboneElementMethods = {
off : Element.stopObserving
};
Element.addMethods(BackboneElementMethods);
Backbone.ajax = function(params) {
var parameters = {
method: params.type,
parameters: params.data,
contentType: params.contentType,
onSuccess: function(response) {
params.success(JSON.parse(response.responseText));
},
onFailure: params.error
};
new Ajax.Request(params.url, parameters);
};
Backbone.View.prototype._ensureElement = function(){
if (!this.el)
{
var attrs = Object.extend({}, this.attributes);
Object.extend(attrs,{id:this.id});
Object.extend(attrs,{'class':this.className});
this.el = new Element(this.tagName,attrs);
}
else
{
this.setElement(this.el,false);
}
}
Backbone.View.prototype.setElement = function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = this.el = $(element);
if (delegate !== false) this.delegateEvents();
return this;
}
Backbone.View.prototype.delegateEvents = function(events) {
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
}
Backbone.$ = $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment