jeudi 12 mars 2015

Object-oriented way to separate page-specific JavaScript in Rails

Assume I have a basic Rails app with three resources: authors, blogs, and books. I created the resources with the scaffold command, so each resource has their own JavaScript file: authors.js, blogs.js, and books.js.


I saw a couple different implementations on how we can keep the global namespace clean for our JavaScript, as well as keep our page-specific JavaScript separate from each other so they don't clash.


Here is my devised implementation. It appears to do what I want, but I wanted to get feedback if this would be considered a bad implementation/bad practice for some reason. I would also welcome other implementations if people have a better way.


For all layouts within app/views/layouts specify this for the body tag:



<body class="<%= controller_name %>">


For the JavaScript code: As we know, all JavaScript in Rails is eventually pulled together into one big JavaScript file. For readability purposes here I pulled all the JavaScript from each of the separate JavaScript files and put them together (within the app I would keep the JavaScript code separate within each of their corresponding js files):



var authorsjs = {
init: function(){
alert("hello from authorjs");
// all author bindings specified here
$("#oneEl").on('click', function(){
alert("oneEl was clicked");
});
},
someAuthorFunc: function(){
alert("someAuthorFunc run");
}
};

$(document).on('page:change', function(){
if($('body').hasClass("authors") == true ){
authorsjs.init();
}
});


var booksjs = {
init: function(){
alert("init booksjs run");
// all books bindings specified here
$("#twoEl").on('click', function(){
alert("twoEl was clicked");
});
},
someBookFunc: function(){
alert("someBookFunc run");
}
};

$(document).on('page:change', function(){
if($('body').hasClass("authors") == true ){
authorsjs.init();
}
});


So as expected, these click events will not work for views associated to blogs, the event bound to #oneEl only works on views associated with authors, and the event bound to #twoEl only works on views associated with books.


Aucun commentaire:

Enregistrer un commentaire