授權方式(Auhorization): CC-BY 4.0

今天在irc #meteor看到的討論,覺得很有趣,所以就做個記錄。
至於meteor的使用心得就慢慢來吧。
我是個懶惰的人。

23:41 < daslicht> I ahve added some data to an item like this:
23:41 < daslicht> <div class="masterItem" data-details-id="{{detailsId}}">
23:41 < daslicht> and a evenmt listener
23:42 < daslicht> inside that event listener I can now access the detailsId like this:
23:42 < daslicht> $(this).attr('detailsId')
23:42 < daslicht> but this did not work:
23:42 < daslicht> $(this).data('detailsId')
23:42 < daslicht> idea why ?

原始的問題大概是這樣,這位老兄想用Meteor Event 去對class是masterItem的div做點事情,但是他發現
jQuery的$(this).data失效了。

問題就在於Meteor Event Handler裡面的$(this) 到底是什麼東西。

23:51 < daslicht> $(this) is NOT refering to the clicked element but to the data item itself which was used to render the item

最後他自己找到的解法。

23:53 < digilord> My next suggestion was going to be to console.log $(this)
23:53 < daslicht> so i dont even need to add a data attribute to each item since it already has access to all data
23:54 < daslicht> already done
23:54 < daslicht> :)
23:55 < daslicht> so my mongo details collection has a detailId property on each document
23:55 < daslicht> so when I use the Meteor Events handler I can just access that property inside the eventhandler like this:
23:55 < daslicht> $(this)[0].detailsId
23:55 < daslicht> FU ummm FREAKING awesome
23:56 < daslicht> *jumps euphoric through the room*

其實一般來說meteor event handler單純要對clicked element做一些取值之類的動作, 是透過這種方式

'click .foo': function(evt) {
    $(evt.target).data("blah");
}

不過這位老兄應該希望是return functions, 所以必須要用$(this)[0].blah...
直接去操作meteor event handler object裡面的東西來用。

Comments

comments powered by Disqus