我刚开始学习 BackboneJS,我正在做一个小样本文档来测试它的工作方式。但是我很难理解它,此时它根本没有任何意义:)
所以,我有下一个文件结构:
/* application.js */
var Application = Application || {};
;(function ( $, window, document, undefined ) {
new Application.ApplicationView();
})( jQuery, window, document );
/* sample.js */
var Application = Application || {};
;(function ( $, window, document, undefined ) {
Application.ApplicationView = Backbone.View.extend({
});
})( jQuery, window, document );
/* utilities.js */
var Application = Application || {};
;(function ( $, window, document, undefined ) {
Application.ApplicationUtilities = Backbone.Collection.extend({
polyfillize : function(tests) {
return _.each(tests, function(obj){
console.log(obj);
Modernizr.load([{
test : _.reduce(obj.test, function(initial_value, current_value){
return initial_value && current_value;
}, 1),
nope : obj.polyfill,
callback: function(url, result, key) {
console.log('Polyfill : ', [ url ]);
}
}]);
});
}
});
})( jQuery, window, document );
/* options.js */
var Application = Application || {};
;(function ( $, window, document, undefined ) {
Application.ApplicationOptions = Backbone.Model.extend({
version : [ 1 ],
prettify : true,
libraries : {
google_code_prettyfier : 'assets/js/libraries/google/prettify.js'
},
dependencies : {
google_code_prettyfier : function() {
return Modernizr.load([{
test : this.prettify,
yep : [ this.libraries.google_code_prettyfier ],
callback: function(url, result, key) {
return window.prettyPrint && prettyPrint();
}
}]);
}
},
polyfills : {
json_polyfill_url : 'http://cdn.chaoscod3r.com/code/polyfills/json3_polyfill.js',
storage_polyfill_url : 'http://cdn.chaoscod3r.com/code/polyfills/localstorage_polyfill.js'
}
});
})( jQuery, window, document );
/* polyfills.js */
var Application = Application || {};
;(function ( $, window, document, undefined ) {
Application.ApplicationPolyfills = Backbone.Model.extend({
loadPolyfills : function() {
return Application.ApplicationUtilities.polyfillize([
{
test : [Modernizr.localstorage, Modernizr.sessionstorage],
polyfill : [Application.ApplicationOptions.polyfills.storage_polyfill_url]
},
{
test : [Modernizr.json],
polyfill : [Application.ApplicationOptions.polyfills.json_polyfill_url]
}
]);
}
});
})( jQuery, window, document );
每个模型都放在它自己的模型文件夹中,每个集合都放在它的集合文件夹中,依此类推。然后我在 DOM 中加载所有脚本,首先是集合,然后是模型、视图,最后是application.js
.
我想要做的是能够将集合用作我可以随时在视图或模型中使用的函数集合,这些选项应该在任何级别和任何集合/模型/视图中都可用。所以就像我的sample.js
文件将包含主视图,它将初始化所有需要在 DOM 加载上运行的东西,比如在必要时加载所有的 polyfill,启用 google 代码美化器等等。
显然在这种状态下没有任何效果,所以如果可能的话,我希望有人更有经验来帮助我,或者可能指向一些与我现在正在尝试做的事情相匹配的教程:)