开发者

Maintaining a javascript "mirror" of your user object

Supposed you have a user who is logined, and has certain attributes - name, nickname, followers, etc which is stored in the backend

You would be using this attributes extensively in javascript display, and having a mirror object in javascript would be very helpful.

How would you do this? I am sure it is a ve开发者_运维技巧ry common problem.


Here's a way you could do it. Your application.js file could make an AJAX call to a User controller that returns @current_user serialized to JSON.

var currentUser;

var success = function(user) {
  currentUser = user;
}

$.get("/users/current/", success);

In your controller:

def current
  respond_to do |format|
    format.js { render :json => @current_user }
  end
end


Have a look at the js-data-helper plugin, which gives you rails helpers that dump data attributes into DOM elements.

It hasn't been updated in a while, but it has lots of features and is well-documented. Also, if you want to go with a custom solution, you can get some pointers by seeing how it's done with this plugin.


Store it in a global hash collection, by placing some javascript in 'views/layouts/application.html.erb'.

That would be my guess =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜