Created
August 15, 2013 00:55
-
-
Save Mparaiso/6237326 to your computer and use it in GitHub Desktop.
Ractive : Backbone collection adaptor.
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
/** | |
* Allow the use of backbone collections instead of models | |
* @see http://experience.eu01.aws.af.cm/3/#backbone for the adaptor in action | |
* @see https://github.com/Rich-Harris/Ractive for details about Ractive | |
*/ | |
;(function(exports){ | |
var Ractive = exports.Ractive; | |
if(Ractive){ | |
Ractive.adaptors.backboneCollection = function(collection,path){ | |
var settingCollection, settingView, setCollection, setView, pathMatcher, pathLength, prefix; | |
if ( path ) { | |
path += '.'; | |
pathMatcher = new RegExp( '^' + path.replace( /\./g, '\\.' ) ); | |
pathLength = path.length; | |
} | |
return { | |
init: function ( view ) { | |
// if no path specified... | |
if ( !path ) { | |
setView = function ( collection ) { | |
if ( !settingCollection ) { | |
settingView = true; | |
view.set( collection.collection.toJSON() ); | |
settingView = false; | |
} | |
}; | |
setCollection = function ( keypath, value ) { | |
if ( !settingView ) { | |
settingCollection = true; | |
collection.reset(value); | |
settingCollection = false; | |
} | |
}; | |
} | |
else { | |
prefix = function ( models ) { | |
var attr, result; | |
result = {}; | |
for (var i=0;i<models.length;i++) { | |
result[ path + i ] = models[ i ]; | |
} | |
return result; | |
}; | |
setView = function ( collection ) { | |
console.log("setting view",arguments); | |
if(typeof arguments[0] === "string") | |
collection = arguments[1]; | |
if ( !settingCollection ) { | |
settingView = true; | |
view.set( prefix( collection.collection.toJSON() ) ); | |
settingView = false; | |
} | |
}; | |
setCollection = function ( keypath, value ) { | |
if ( !settingView ) { | |
if ( pathMatcher.test( keypath ) ) { | |
settingCollection = true; | |
//collection.set( keypath.substring( pathLength ), value ); | |
collection.reset(value); | |
settingCollection = false; | |
} | |
} | |
}; | |
} | |
collection.on( 'all', setView ); | |
view.on( 'set', setCollection ); | |
// initialise | |
//view.set( path ? prefix( collection.attributes ) : collection.attributes ); | |
view.set( path ? prefix( collection.toJSON() ) : collection.toJSON() ); | |
}, | |
teardown: function ( view ) { | |
collection.off( 'change', setView ); | |
view.off( 'set', setCollection ); | |
} | |
}; | |
}; | |
} | |
}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment