Rails turbolinks breaking pnotify

坚强是说给别人听的谎言 提交于 2019-12-10 11:24:53

问题


In my rails application, I have it so that when you vote, subscribe or unsubscribe from a list, it will show a popup using pnotify.

This works fine until the user navigates to a different page, and now it is no longer working. This only works when page is loaded or reloaded.

I know this is because turbolinks in a rails 4 application but it seems to execute all my other javascript code apart from the pnotify.

Additional info..

The subscribe/unsubscribe and vote buttons have the method post and are executed remotely which means I have a seperate file names subscribe.js.erb, unsubscribe.js.erb and vote.js.erb that handle the execution of the javascript code when the user has clicked on the buttons.

this is an example of how I am creating a new pnotify object:

new PNotify({
    title:  "Subscribed!",
    text: "<%= @message %>",
    type: 'info',
    opacity: .8,
    animation: {
        effect_in: 'show',
        effect_out: 'slide'
    },
    buttons: {
        sticker: false
    }
}).get().click(function() {
            $(this).remove();
        });

I am also using a gem for pnotify called gem 'pnotify-rails'


回答1:


I've had the same issues, but that happens because PNotify loses its context, as you can see in that line the plugin assign the context as $('body'), but when you navigate using turbolink, the body is replaced so the context is lost.

What you need to do?

You need to assign the context in turbolink's event 'page:load'

$(document).on('page:load',function(){
	PNotify.prototype.options.stack  = {
		dir1: "down",
		dir2: "left",
		push: "bottom",
		spacing1: 25,
		spacing2: 25,
		context: $("body")
    }
        
});


来源:https://stackoverflow.com/questions/28078480/rails-turbolinks-breaking-pnotify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!