2016-06-11 46 views
1

調用一個類的方法coffeescript..and我是新來的CoffeeScript ...CoffeeScript的類 - 調用從我已經重寫我的嵌入式JS在我的Rails應用程序的其他

我的做法是,這些文章的結構:

我的代碼:

s = undefined 
class App.PhotoLike 

    settings: 
    modalElement: $('#myModal') 
    likeButtonId: '#like' 
    photo_id: $('.image_info').attr('photo_id') 
    numberOfLikes: $('#likes_num') 

    constructor: (@el) -> 
    console.log('constructor called') 
    s = @settings 
    @bindUIActions() 
    return this 


    bindUIActions: -> 
    console.log('bindUIActions called') 
    $('#myModal').on 'click', '#like', -> likePhoto() 
    $(document).on "page:change", -> pageChange() 


    pageChange: -> 
    console.log('pageChange called') 
    photo = new App.Photo 

    likePhoto: -> 
    console.log('likePhoto called') 
    url = '/photos/' + s.photo_id + '/like' 
    $.get url, (data) -> 
     s.numberOfLikes.html data['likes'] + ' likes' 
     $(s.likeButtonId).toggleClass 'btn-success' 

這是獲取與阿賈克斯loded模型的一部分,一旦調用成功,我做我創建上面的類(實例):

new (App.PhotoLike) 

我的問題。 模態得到加載一切似乎很好。但是,當我觸發事件:

$('#myModal').on 'click', '#like', -> likePhoto() 

我得到:

photo.like.self-942fcd8….js?body=1:25 Uncaught ReferenceError: likePhoto is not defined 

所以,它不知道likePhoto功能。我曾嘗試調用this.likePhoto和@likePhoto,但是這指的是觸發事件的按鈕元素。

那麼我該如何做到這一點? 歡迎使用其他方法。我不太確定我是否需要班級...但我真的想要結構化代碼...

回答

1

likePhoto()是我們的對象/類App.PhotoLike的函數。你稱它爲一個本地函數。

你可以做這樣的事情,而不是

bindUIActions: -> 
    _this = this #this will change inside, so we have to have a reference to our object here 
    console.log('bindUIActions called') 
    $('#myModal').on 'click', '#like', -> _this.likePhoto() 
    ... 

讓我知道,如果它的工作原理。

+0

Yay ..它的作品...太簡單了!你能幫助我解決後續問題嗎?我如何讓s(設置)變量在課堂上按預期工作 – martin

+0

對不起,你的意思是什麼意思。你想實現什麼? – Kumar

+0

我有設置變量在類的頂部,我設置了我需要的各種設置。所以我想在課堂上使用這些設置Settings.url – martin

0

大廈庫馬爾的回答,您可以使用脂肪箭頭綁定@this

bindUIActions: => 
    console.log('bindUIActions called') 
    $('#myModal').on 'click', '#like', -> @likePhoto() 

嘗試。

相關問題