Randy Schmidt on 26 Jun 2008 09:55:47 -0700 |
Hi Everybody, I just wanted to follow with a solution to one of the problems with using jQuery unobtrusively with rails, and that was RJS. RJS lets you update multiple items on a page by sending javascript back to the browser which gets evaluated. RJS only works with Prototype (there may be plugins that fix this) so you are kind of SOL with other frameworks. A way around this in Rails >= 2.0 is to use .js.erb templates which let you write javascript and spit out data from your app or render partials. You still want to keep most of your js in externally linked files so what I do is create functions that hide away the implementation of what I want to do. contents of index.js.erb: updateFolloweesStatus(<%= partial 'users/status', :collection => current_user.followees %>) updateCurrentUserDisplayStatus(<%= partial 'users/status', :object => current_user %>) updateCurrentUserInputStatus('<%= current_user.status %>') The JS: function updateFolloweesStatus(txt) { $('#their_status').html(txt) } function updateCurrentUserDisplayStatus(txt) { $('#my_status').html(txt) } function updateCurrentUserInputStatus(txt) { // if the field isn't focused, update it (ie, don't clobber something that will be changed soon) if ($('#user_status.focused').size() == 0) { $('#user_status').val(txt) } } Helpers: # from Dan Webb's MinusMOR plugin # enhanced with ability to detect partials with template format, i.e.: _post.html.erb def partial(name, options={}) old_format = self.template_format self.template_format = :html js render({ :partial => name }.merge(options)) ensure self.template_format = old_format end def js(data) if data.respond_to? :to_json data.to_json else data.inspect.to_json end end Hopefully this is helpful and closes the loop on the whole "update more than one element on the page" issue. Let me know if you have any questions. Thanks, -- umlatte llc Randy Schmidt randy@umlatte.com www.umlatte.com 267-334-6833 _______________________________________________ To unsubscribe or change your settings, visit: http://lists.phillyonrails.org/mailman/listinfo/talk
|
|