这两天在重看 @huacnlee 的视频http://railscasts-china.com/episodes/live-show-with-huacnlee
我的理解是这样的:* 在topics/show.html.erb
里面调用topics_helper.rb
的方法,生成了一个Link
link_to raw([icon,"关注"].join(" ")), "#", :onclick => "return Topics.follow(this);", 'data-id' => topic.id, 'data-followed' => (class_name == "followed"), :rel => "twipsy"
在topics.coffee
里面定义了Topics.fllow
这个事件(函数?)
# TopicsController 下所有页面的 JS 功能window.Topics = ... follow : (el) -> topic_id = $(el).data("id") followed = $(el).data("followed") if followed $.ajax url : "/topics/#{topic_id}/unfollow" type : "POST" $(el).data("followed", false) $("i",el).attr("class", "icon small_follow") else $.ajax url : "/topics/#{topic_id}/follow" type : "POST" $(el).data("followed", true) $("i",el).attr("class", "icon small_followed") false
到这里我没弄明白的是* windows.Topics = ...
这句话是定义了一个变量?* 如果我自己想实现一个最简单的js
的hello world
的话,只需要这两步就可以么?
实际上我自己尝试了一下,但没有成功
rails new coffee_test
rails g controller topics index
在topics/index.html.erb
里面生成Link
<%= link_to 'test', “#", :onclick => "return Topics.sayHello();" %>
在topics.coffee
里面定义函数
windows.Topics = sayHello: -> alert('Topics say : hello!!!')
打开localhost:3000/topics/index
后,点击test
完全没反映,也没有JS错误
请问我的理解哪里出错了?
原文地址:ruby-china 里面,ajax 如何实现的?, 感谢原作者分享。 读书破万卷,下笔如有神。