Rails 中的 RJS/Javascript 约定
我开始研究 Rails 中 RJS 和 Prototype/jQuery 的整个世界,但我有点困惑。 对于在哪里使用其中之一似乎没有明确的界限。
假设我想要“活跃、热门、一周”选项卡之一,就像 SO 上的选项卡一样。 当按下其中之一时,我想从我所在的CSS类中删除一个CSS类(例如“active-tab”)并将其添加到我点击的CSS类中。 然后我还想重新加载包含项目的 div 并将新项目放入其中。
似乎在纯 javascript 中最容易完成类更改,例如将代码放入 application.js 中,然后使用内容更新 div 显然在 RJS 中最简单。 但是人们应该做什么呢?
I'm starting to look into the whole world of RJS and Prototype/jQuery in Rails and am a little bit confused. There seems to be no clear line of where to use one or the other.
Say I wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them, I want to remove a CSS class (like "active-tab") from the one I was on and add it to the one I clicked on. Then I also want to reload the div containing the items and put in the new items into it.
Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what should one do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您习惯于编写 JavaScript,那么请务必使用 JavaScript。 这并没有什么问题; 您不必仅仅因为 RJS 存在就使用它。 事实上,您可能会发现它的抽象妨碍了您。
但是,如果您更愿意编写生成 JavaScript 的 Ruby 代码,就像您在 ActiveRecord 迁移中编写生成 SQL 的 Ruby 代码一样,那么 RJS 就是适合该工作的工具。 或者您可以同时使用 RJS 来处理相当简单的事情,然后使用 JavaScript 来处理更复杂的行为。 使用你觉得合适的东西。
If you're comfortable with writing JavaScript then by all means use JavaScript. There's nothing wrong with that; you don't have to use RJS just because it exists. In fact you'll probably find that its abstractions get in the way.
However, if you'd rather write Ruby code that generates JavaScript, just as you write Ruby code that generates SQL in ActiveRecord Migrations, then RJS is the right tool for the job. Or you can use both: RJS for fairly simple things and then drop down to JavaScript for more complex behaviour. Use what feels right to you.
如果您想让用户能够直接链接到生成的页面,那么一定要选择静态页面。 使用 AJAX 会破坏后退按钮,除非您使用类似 Really Simple History (这不是 100% 跨浏览器),因此 使用 JS 路线进行页面导航几乎肯定会导致一些用户问题。
也就是说,我认为您已经讨论过的内容就很好 - 只需在 RJS 文件中进行类更改,然后您甚至可能会发现使用 page.replace 和部分内容更新 div 内容很有用:
If you want to give users that ability to link to the generated page directly, then definitly go for a static page. Using AJAX breaks the back button unless you use something like Really Simple History (which is not 100% cross browser), so going the JS route with your page navigation will almost certainly cause some of your users problems.
That said, what you have discussed already would be fine, I think - just have a class change in your RJS file, then you might even find it useful to update the div contents using page.replace and a partial: